首页 > 解决方案 > 在深度异步调用中查找父方法的属性

问题描述

我正在寻找一种方法来为我的方法“添加一些上下文”以进行调试。尽管使用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在父方法上进行装饰?在同步世界中,上述内容将起作用。在异步世界中,堆栈跟踪会丢失。有任何想法吗?

解决方案不一定必须涉及使用属性。

标签: c#asynchronousasync-await

解决方案


如果我正确理解您的用例,您正在寻找的是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);
}

推荐阅读