25
2016
11

.Net中偶尔需要使用异步的处理

我们知道程序中使用异步、多线程会提高程序的响应速度,但也不能无限使用多线程,这在高峰会造成系统cpu上升,系统卡顿,这就需要我们自己来控制开启的线程数,不多说看代码。

        private static int threadCountByOrderId = 0;
        private static int maxThreadCountByOrderId = 30;
        public bool dealorder(int OrderId)
        {
            var threadNumber = Interlocked.Exchange(ref threadCountByOrderId, threadCountByOrderId);
            if (threadCountByOrderId > maxThreadCountByOrderId)
            {
                return OrderChangePushToBigDataImpService.PushOrderToBigData(OrderId, Logger);
            }
            else
            {
                Task.Factory.StartNew(() =>
                {
                    Interlocked.Increment(ref threadCountByOrderId);
                    try
                    {
                        using (var context = MefInjectionProvider.CreateContext())
                        {
                            var NewOrderChangePushToBigDataImpService = context.Value.GetExport<IOrderChangePushToBigDataImpService>();
                            NewOrderChangePushToBigDataImpService.PushOrderToBigData(OrderId, Logger);
                        }
                    }
                    finally
                    {
                        Interlocked.Decrement(ref threadCountByOrderId);
                    }
                });
                return true;
            }
        }

这样就能控制线程数据了



版权声明:
作者:真爱无限 出处:http://www.pukuimin.top 本文为博主原创文章版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接.
« 上一篇下一篇 »

相关文章:

评论列表:

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。