线程的执行上下文 [英] ExecutionContext of Threads

查看:209
本文介绍了线程的执行上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ExecutionContext.SuppressFlow();的目的是什么?在以下代码中,确切地被抑制了什么?

What's the purpose of ExecutionContext.SuppressFlow();? In the following code what exactly gets suppressed?

我有这个测试代码...

I've this test code...

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之类的功能内部. 它的一部分是:

The details of ExecutionContext are very obscure, buried deep inside features like .NET Remoting and WCF. What is part of it is:

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

CultureInfo不是其中的一部分,如果您更改主线程的默认区域性,则可能是一个相当大的问题.除非您显式编写代码对其进行切换,否则没有什么好方法可以确保其他线程以该区域性运行.鉴于.NET易于在线程池线程上运行异步回调,因此这并不总是可行的.它们将被初始化为系统默认区域性.

CultureInfo is not part of it, which can be a considerable problem if you change your main thread's default culture. There is no good way to ensure other threads run with that culture unless you explicitly write the code to switch them. That's not always practical, given that .NET is apt to run async callbacks on threadpool threads. They will be initialized to the system default culture.

.NET 4.5中的CultureInfo.DefaultThreadCurrentCulture属性已解决此问题.

this problem got fixed in .NET 4.5 with the CultureInfo.DefaultThreadCurrentCulture property.

Edit2:在.NET 4.6中进行了更彻底的修复,现在文化可以按预期进行.

fixed much more thoroughly in .NET 4.6, culture now flows as expected.

这篇关于线程的执行上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆