相关疑难解决方法(0)

将ThreadStatic变量与async/await一起使用

使用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)

c# multithreading synchronization async-await

35
推荐指数
4
解决办法
1万
查看次数

了解C#5 async/await中的上下文

我是否正确async/await本身与并发/并行无关,只不过是继续传递样式(CPS)实现?真正的线程是通过传递/恢复的SynchronizationContext实例来执行的await

如果这是正确的,我有以下问题SynchronizationContext:
它保证在同一个线程上执行继续.

但是,是否有任何保证线程的上下文信息是持久的?我的意思是Name,CurrentPrincipal,CurrentCulture,CurrentUICulture,等它是否依赖于框架(ASP.NET,WinForms的,WCF,WPF)?

c# multithreading conceptual async-await asp.net-4.5

23
推荐指数
1
解决办法
2万
查看次数

等待应该恢复Thread.CurrentContext?

此问题相关,

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)

c# async-await

7
推荐指数
1
解决办法
1656
查看次数