在深度异步调用中找到父方法的属性

时间:2018-09-08 15:41:06

标签: c# asynchronous async-await

我正在寻找一种为调试目的向我的方法“添加一些上下文”的方法。即使将StackTrace与同步代码配合使用也可以,但在进行异步处理时,事情自然会停止。我完全理解为什么,但是我找不到解决此问题的好方法。

[Scope("method 1")]
private async Task Method1()
{
    // ... other awaited calls
    await DoWork();
}

[Scope("method 2")]
private async Task Method2()
{
    // ... other awaited calls
    await DoWork();
}

private async Task DoWork()
{
    // Get ScopeAttribute from parent method
    var description = new StackTrace()
      .GetFrames()
      ?.SelectMany(f => f.GetMethod().GetCustomAttributes(typeof(ScopeAttribute), false))
      .Cast<ScopeAttribute>()
      .FirstOrDefault()?.Description;
}

如何使用父方法修饰的ScopeAttribute?在同步的世界中,上述方法就可以了。在异步世界中,堆栈跟踪会丢失。有什么想法吗?

解决方案不必一定要使用属性。

1 个答案:

答案 0 :(得分:2)

如果我正确理解了您的用例,那么您正在寻找的是AsyncLocal

private static AsyncLocal<string> _scope = new AsyncLocal<string>();

private async Task Method1()
{
    _scope.Value = "method 1";

    // ... other awaited calls
    await DoWork();
}

private async Task Method2()
{
    _scope.Value = "method 2";

    // ... other awaited calls
    await DoWork();
}

private async Task DoWork()
{
    Console.WriteLine(_scope.Value);
}
相关问题