基于我所读过的所有内容,下面的测试方法应该通过。我想弄明白为什么失败了。私有异步方法中的第一个断言按预期传递。但是,一旦任务被返回并等待。在检索时,CallContext中设置的值现在为null。
[TestMethod]
public void LogicalCallContextBlockingTest()
{
PerformSimpleAsyncWork().Wait();
var result = CallContext.LogicalGetData("test");
Assert.AreEqual(result, "expected");
}
private async Task PerformSimpleAsyncWork()
{
await Task.Run(() =>
{
System.Threading.Thread.Sleep(100);
CallContext.LogicalSetData("test", "expected");
var result = CallContext.LogicalGetData("test");
Assert.AreEqual(result, "expected");
});
}发布于 2014-10-03 18:00:10
使用async关键字修饰的方法在调用时创建子上下文。对此子上下文所做的任何更改都不会传播到父上下文。
因此,PerformSimpleAsyncWork获得一个子上下文,该子上下文可以看到调用方在上下文中放置的任何内容,但是调用方(LogicalCallContextBlockingTest)将无法使用它所做的任何更改。
如果您需要更多的信息,Stephen有一个关于这种行为的good writeup。
https://stackoverflow.com/questions/26184161
复制相似问题