关于WEBAPI 开启后CPU占用居高不下的解决方法

关于WEBAPI 开启后CPU占用居高不下的解决方法

近期做了一个WPF+webapi+selfhost的项目,发现当UI不进行任何操作时CPU占用竟然也高达25%,后台一直在执行这样一个线程:

                    Thread td = new Thread(new ThreadStart(
            () =>
            {
                Assembly.Load("Hisense Medical QCS, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
                //HttpSelfHostConfiguration configuration = new HttpSelfHostConfiguration("http://localhost:12340");
                HttpSelfHostConfiguration configuration = new HttpSelfHostConfiguration("http://localhost:" + ConfigurationSettings.AppSettings["port"]);
                using (HttpSelfHostServer httpServer = new HttpSelfHostServer(configuration))
                {
                    httpServer.Configuration.Routes.MapHttpRoute(
                        "DefaultApi",
                        "api/{controller}/{id}/{administrator}",
                        new { id = RouteParameter.Optional, administrator = RouteParameter.Optional });
                    httpServer.OpenAsync().Wait();

                    while (true)
                    {                           
                    }                        
                }                    
            }
        ));

如果没有while(true)这个死循环,API接口无法被调用,后来在网上找到了解决方法,在死循环中让线程休眠1毫秒就可以了。

                    Thread td = new Thread(new ThreadStart(
            () =>
            {
                Assembly.Load("Hisense Medical QCS, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
                //HttpSelfHostConfiguration configuration = new HttpSelfHostConfiguration("http://localhost:12340");
                HttpSelfHostConfiguration configuration = new HttpSelfHostConfiguration("http://localhost:" + ConfigurationSettings.AppSettings["port"]);
                using (HttpSelfHostServer httpServer = new HttpSelfHostServer(configuration))
                {
                    httpServer.Configuration.Routes.MapHttpRoute(
                        "DefaultApi",
                        "api/{controller}/{id}/{administrator}",
                        new { id = RouteParameter.Optional, administrator = RouteParameter.Optional });
                    httpServer.OpenAsync().Wait();
                    while (true)
                    {       
                         Thread.Sleep(1);                    
                    }                        
                }                    
            }
        ));
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值