如何使 AsyncLocal 流向兄弟姐妹?

Vla*_*lad 8 c# asynchronous task-parallel-library async-await

这是一个非常简单的示例,我希望可以使用,但是...

    static AsyncLocal<bool> _value = new AsyncLocal<bool>();

    static void Main(string[] args)
    {
        A().Wait();
    }

    static async Task A()
    {
        await B();
        await C();
    }

    static async Task B()
    {
        _value.Value = true;
    }

    static async Task C()
    {
        if (!_value.Value) throw new Exception();
    }
Run Code Online (Sandbox Code Playgroud)

那么是否有可能以某种方式在方法B中存储一些东西,以便值在 中可用C?我只需要通过异步流传递它(不要ThreadStatic)。

Vla*_*lad 6

所以这就是我发现的:

  • AsyncLocal 仅以一种方式传输 - 从外层到内层异步方法,所以我添加了一个 B_Start在“顶级”级别初始化本地方法。
  • 即使对于已经初始化的局部变量,内部方法内的更改也不会传回,但您可以改变引用类型容器上的字段。

工作代码:

    class Container<T>
    {
        public T Value { get; set; }
    }
    static AsyncLocal<Container<bool>> _value = new AsyncLocal<Container<bool>>();

    static void Main(string[] args)
    {
        A().Wait();
    }

    static async Task A()
    {
        await B_Start();
        await C();
    }

    static Task B_Start()
    {
        _value.Value = new Container<bool>();
        return B();
    }

    static async Task B()
    {
        _value.Value.Value = true;
    }

    static async Task C()
    {
        if (!_value.Value.Value) throw new Exception();
    }
Run Code Online (Sandbox Code Playgroud)