gpt4 book ai didi

c# - CallContext 正在转发之前设置的数据

转载 作者:太空宇宙 更新时间:2023-11-03 12:12:23 26 4
gpt4 key购买 nike

在这种情况下,我看到线程的 CallContext 正在后续调用中转发数据。

考虑我有一个简单的 API,当它被查询时,将使用以下方式将一个数据条目设置到 CallContext 中:

// entry to the API execution within OnStartProcessingRequest method of DataService
if(CallContext.LogicalGetData("data") != null)
CallContext.LogicalSetData("data", someValue)
print("data " + CallContext.LogicalGetData("data"))

当我在一些 API 查询后查看日志时,我看到了类似的日志。

|线程 |日志 |
| 237 |数据 23 |
| 145 |数据 19 |
|第872章数据 78 |
| 237 |数据 23 |

我担心的是,为什么 ID 为 237 的线程获取旧数据?即 23
我确定控件没有进入 LogicalSetData 代码块,因为它已经有数据。

我不确定为什么会这样?谁能帮我解决这个问题?

该服务是一个 WCF 数据服务。正在从 postman REST 客户端进行调用。

最佳答案

考虑切换到 OperationContext,因为它是为特定请求存储数据的内置自然上下文
CallContext.GetData 将获取数据是通过同一线程的 SetData 设置的。通过 CallContext.LogicalSetData 存储的数据被认为是本地“逻辑线程”。也就是说,通过 CallContext.LogicalSetData 存储的任何数据都将“流”到任何子线程。如果您在同一线程或任何子线程中调用 CallContext.LogicalGetData,您将获得该线程(或父线程)调用 CallContext.LogicalSetData 时存储的数据。更好的描述in this great article .
我找不到任何关于每次请求启动时 CallContext 必须干净的信息,但我找到了 this old article ,描述自定义 ICallContextInitializer 实现。它说:

WCF by default is more frugal than other stacks, such as ASP.NET, when it comes to protecting state. Saving and restoring lots of thread-local settings takes time regardless of whether you actually did something with those settings or not. WCF tries not to do as much on your behalf so that you don't have to pay for cleanup unless you're using those features. It does however give you the hooks necessary to arrange for this cleanup to take place at the appropriate time.

关于c# - CallContext 正在转发之前设置的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51474074/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com