使用C#中的新async/await关键字,现在会对使用ThreadStatic数据的方式(以及何时)产生影响,因为回调委托在与async启动的操作不同的线程上执行.例如,以下简单的控制台应用程序:
[ThreadStatic]
private static string Secret;
static void Main(string[] args)
{
Start().Wait();
Console.ReadKey();
}
private static async Task Start()
{
Secret = "moo moo";
Console.WriteLine("Started on thread [{0}]", Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("Secret is [{0}]", Secret);
await Sleepy();
Console.WriteLine("Finished on thread [{0}]", Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("Secret is [{0}]", Secret);
}
private static async Task Sleepy()
{
Console.WriteLine("Was on thread [{0}]", Thread.CurrentThread.ManagedThreadId);
await Task.Delay(1000);
Console.WriteLine("Now on thread [{0}]", Thread.CurrentThread.ManagedThreadId);
}
Run Code Online (Sandbox Code Playgroud)
将输出以下内容:
Started on thread [9]
Secret is [moo moo]
Was on thread [9]
Now …Run Code Online (Sandbox Code Playgroud) 我是否正确async/await本身与并发/并行无关,只不过是继续传递样式(CPS)实现?真正的线程是通过传递/恢复的SynchronizationContext实例来执行的await?
如果这是正确的,我有以下问题SynchronizationContext:
它保证在同一个线程上执行继续.
但是,是否有任何保证线程的上下文信息是持久的?我的意思是Name,CurrentPrincipal,CurrentCulture,CurrentUICulture,等它是否依赖于框架(ASP.NET,WinForms的,WCF,WPF)?
与此问题相关,
是await应该恢复的背景下(特别是通过上下文所代表Thread.CurrentContext的)ContextBoundObject?考虑以下内容:
class Program
{
static void Main(string[] args)
{
var c1 = new Class1();
Console.WriteLine("Method1");
var t = c1.Method1();
t.Wait();
Console.WriteLine("Method2");
var t2 = c1.Method2();
t2.Wait();
Console.ReadKey();
}
}
public class MyAttribute : ContextAttribute
{
public MyAttribute() : base("My") { }
}
[My]
public class Class1 : ContextBoundObject
{
private string s { get { return "Context: {0}"; } } // using a property here, since using a field causes things …Run Code Online (Sandbox Code Playgroud)