c# - 在深度异步调用中查找父方法的属性
问题描述
我正在寻找一种方法来为我的方法“添加一些上下文”以进行调试。尽管使用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
在父方法上进行装饰?在同步世界中,上述内容将起作用。在异步世界中,堆栈跟踪会丢失。有任何想法吗?
解决方案不一定必须涉及使用属性。
解决方案
如果我正确理解您的用例,您正在寻找的是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);
}
推荐阅读
- solr - 在云模式下运行 Solr 自定义过滤器
- c# - dc.BeginDialogAsync:“值不能为空。\n参数名称:选项”
- python - 无法用 seaborn 地块来评估斧头对象
- python - 如何自动复制 - 粘贴 - 运行 .exe 文件?
- javascript - 带有数组值的jQuery排序元素没有html属性
- python - 如何根据特定字符串匹配将特定字符串附加到另一个字符串?
- c# - 没有递归的 C# 字符串数组修改
- azure - 如何将源中的行键映射到接收器中的行键?没有按预期工作
- node.js - 使用 multer-s3 将大型视频文件上传到 s3
- python - Treating a percentage over 100% as a double digit %