我们知道程序中使用异步、多线程会提高程序的响应速度,但也不能无限使用多线程,这在高峰会造成系统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; } }
这样就能控制线程数据了
评论列表: