.NET线程池和执行上下文,ExecutionContext类

时间:2016-01-12 19:16:03

标签: c# .net multithreading

第27章中有一条声明,CLR通过里希特写的c#书:

  

您可以使用ExecutionContext类来抑制执行上下文的流动,从而提高应用程序性能。对于服务器应用程序,性能提升可能非常大。

其次是示例:

CallContext.LogicalSetData("Name", "Jeffrey");

//Initiate some work to be done by thread pool
ThreadPool.QueueUserWorkItem(
           state => Console.WriteLine("Name={0}", CallContext.LogicalGetData("Name")
));

接下来是第二部分:

//Now suppress the flowing of the Main thread's execution context
ExecutionContext.SuppressFlow();

//Initiate some work to be done by thread pool
ThreadPool.QueueUserWorkItem(
           state => Console.WriteLine("Name={0}", CallContext.LogicalGetData("Name")
));

ExecutionContext.RestoreFlow();

结果:

Name=Jeffrey
Name=

子线程已丢失其上下文(在示例的第2部分中),因为副作用参数在压制后丢失。但是我们节省了CPU时间(在我的情况下节省了大约10%的CPU时间)。

  • 您是否使用ExecutionContext.SuppressFlow()方法来减少CPU处理时间?
  • 除了丢失输入参数和上下文之外还有哪些其他缺点?
  • 您如何建议确定时间执行差异?

0 个答案:

没有答案