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

CallContext is carrying foreward the previous data which was set

在这种情况下,我看到线程的 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 数据服务。正在从邮递员 REST 客户端进行调用。

考虑切换到 OperationContext,因为它是为特定请求存储数据的内置自然上下文
CallContext.GetData将从同一线程获取通过 SetData 设置的数据。通过 CallContext.LogicalSetData 存储的数据被认为是 "logical thread" 本地的。也就是说,通过 CallContext.LogicalSetData 存储的任何数据对于任何子线程都将是 "flowed"。如果您在同一线程或任何子线程中调用 CallContext.LogicalGetData,您将获得该线程(或父线程)对 CallContext.LogicalSetData 的调用所存储的数据。更好的描述 in this great article.
I was unable to find any information that CallContext must be clean on each request start, however I found 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.