在以下示例中,该方法公开为 WCF 服务操作,并且该服务托管在 IIS 中。
进入该函数时,WebOperationContext.Current 将按预期设置。然而,等待完成等待后,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
}
这似乎是一个缺点,所以我想知道是否有人意识到这一点以及是否有任何好的方法可以解决它。我意识到我可以在局部变量中缓存对 context 的引用,但这看起来不太好。
Update
一种有效的方法是
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
以及。看这个帖子 https://stackoverflow.com/questions/12797091/operationcontext-current-is-null-after-first-await-when-using-async-await-in-wcf(请注意,Jon Cole 是 MS WCF 团队的成员)。
同时,您可以捕获变量中的值(这提高了可测试性,也是我推荐的),将其添加到LogicalCallContext
,或安装您自己的SynchronizationContext
(这会很棘手,因为您托管在 IIS 中,它使用自己的SynchronizationContext
).
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)