c# – Threads的ExecutionContext

前端之家收集整理的这篇文章主要介绍了c# – Threads的ExecutionContext前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
ExecutionContext.SuppressFlow();的目的是什么?在下面的代码中究竟被压制了什么?

我有这个测试代码……

protected void btnSubmit_Click(object sender,EventArgs e)
{
   Thread[] th = new Thread[100];
   Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-GB");

   AsyncFlowControl cntrl = ExecutionContext.SuppressFlow();
   for (int i = 0; i < th.Length; i++)
   {                   
      th[i] = new Thread(new ParameterizedThreadStart(ThreadMethod));
      th[i].Name = "Thread #" + (i+1).ToString();                
      th[i].Start((i+1).ToString());
   }
   ExecutionContext.RestoreFlow();

   foreach (Thread t in th)            
   {
      t.Join();
   }
   Response.Write(response);
}


String response = null;
Random rnd = new Random(1000);
private void ThreadMethod(object param)
{   
   if (param != null)
   {
      string temp = param as string;
      if (temp != null)
      {
         //To test what is the current culture I get for this thread execution
         System.Globalization.CultureInfo info = Thread.CurrentThread.CurrentCulture;
         for (int i = 0; i <= 10; i++)
         {
            Thread.Sleep(rnd.Next(2000));
            response += Thread.CurrentThread.ManagedThreadId.ToString() + ":" 
                     + Thread.CurrentThread.Name + ": " + temp + "<br/>";
         }
      }
   }
}

解决方法

ExecutionContext的细节非常模糊,深埋在.NET Remoting和WCF等功能中.
它的一部分是:

> HostExecutionContext
> IllogicalCallContext,Remoting使用的线程特定数据的存储库
> LogicalContext,如上所述
> SecurityContext
> SynchronizationContext

CultureInfo不是它的一部分,如果你改变主线程的默认文化,这可能是一个相当大的问题.除非您明确编写代码来切换它们,否则没有好办法确保其他线程与该文化一起运行.鉴于.NET易于在线程池线程上运行异步回调,这并不总是实用的.它们将初始化为系统默认文化.

编辑:使用CultureInfo.DefaultThreadCurrentCulture属性在.NET 4.5中修复此问题.

Edit2:在.NET 4.6中更加彻底地修复,文化现在按预期流动.

猜你在找的C#相关文章