c# - 如何使一段数据可供调用堆栈下方的其他函数使用?

标签 c# asp.net-core .net-core

对于某些特定的日志记录要求,我想生成一个变量,也许是一个让我识别该函数的 GUID。 然后,我想在调用堆栈中的另一个函数中访问该变量而不修改调用堆栈中原始函数的函数签名

这可能吗或者有意义吗?

For context :

I am generating some logs that I would like to "link" the caller to the function being called down the stream. In the caller, I am able to write some logs or assign some specific ID to the current function. However, down the callstack, It seems like im possible to access any information from the "Caller" apart from basic informations using StackTrace

Lets imagine I have a some call chains like this

A()

=> B()

=> => C()

How would I know that the current instance of C() is being invoked by the specific A() call without passing the A() 's GUID down the call stack to B() and then to C() ?

我做了一些研究,但结果似乎很旧,不一定符合当前情况 Pass values to function further down the call stack

最佳答案

看看可用的解决方案,似乎这是一个广泛使用的功能。对于 NET 标准,System.Runtime.Remoting.Messaging.CallContext被使用

Provides a set of properties that are carried with the execution code path.

对于 .NET Core,System.Threading.AsyncLocal<T>可用

Represents ambient data that is local to a given asynchronous control flow, such as an asynchronous method.

完整的实现可以在 this blog 中看到。

人们还可以从 NLog 的 NestedDiagnosticsLogicalContext 中获得灵感这似乎利用了上述两种解决方案来在逻辑范围内实现全面的消息传递机制

关于c# - 如何使一段数据可供调用堆栈下方的其他函数使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59825934/

相关文章:

c# - 使用匿名委托(delegate)返回对象

c# - AsNoTracking() 和包含

c# - .NET 8 IEnumerable 接口(interface)的序列化/反序列化

c# - Razor 模板 : Cannot find compilation library location for package

c# - 使用 C# - .Net Core 进行单元测试 RabbitMQ 推送

.net-core - .net核心版本生成本地化文件夹

c# - 处理奇数场偏移

c# - 如何为 FsCheck 测试生成空字符串

azure - 如何将 appsettings.json 设置包含到 Azure DevOps 构建和发布管道中

c# - 如何将 .xproj 引用到 .csproj 中?