在下面的示例中,该方法公开为 WCF 服务操作,并且该服务托管在 IIS 中。 在进入该函数时,WebOperationContext.Current 按预期设置。但是,在 await 完成等待后,WebOperationContext.Current 设置为 null。
public async Task TestAsync()
{
//WebOperationContext.Current is set
Task t = new Task(()=>Thread.Sleep(10000));
t.Start();
await t;
//WebOperationContext.Current is null
}
这似乎是一个缺点,所以我想知道是否有人意识到这一点,以及是否有任何好的方法可以解决它。我意识到我可以在局部变量中缓存对 conext 的引用,但这看起来不太好。
更新
一种有效的方法是
public async Task TestAsync()
{
WebOperationContext ctx = WebOperationContext.Current;
Task t = new Task(()=>Thread.Sleep(10000));
t.Start();
await t;
//ctx is set
}
而且,正如其他人所暗示的,我可以做到这一点
public async Task TestAsync()
{
CallContext.LogicalSetData("WebOperationContext.Current", WebOperationContext.Current);
Task t = new Task(()=>Thread.Sleep(10000));
t.Start();
await t;
WebOperationContext ctx = (WebOperationContext)CallContext.LogicalGetData("WebOperationContext.Current");
}
它们在性能和线程安全方面的影响是什么?
最佳答案
我听说 WCF 团队正在考虑 OperationContext.Current
的解决方案,我希望他们也能解决 WebOperationContext.Current
。参见 this SO post (请注意,Jon Cole 是 MS WCF 团队的一员)。
与此同时,您可以捕获变量中的值(这提高了可测试性,这是我推荐的),将其添加到 LogicalCallContext
,或者安装您自己的 SynchronizationContext
(这会很棘手,因为您托管在使用自己的 SynchronizationContext
的 IIS 中)。
关于c# - 异步 WCF 方法 WebOperationContext 在等待后为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13290146/