简体   繁体   English

异步WCF方法等待后,WebOperationContext为null

[英]async WCF method WebOperationContext is null after await

In the following example, the method is exposed as a WCF service operation and the service is hosted in IIS. 在以下示例中,该方法作为WCF服务操作公开,并且该服务在IIS中承载。 On entry into the function the WebOperationContext.Current is set as expected. 在进入函数时,WebOperationContext.Current按预期设置。 After the await has finished waiting, however, the WebOperationContext.Current is set to null. 然而,在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
    }

This would seem to be a shortcoming, so I wondered if anyone was aware of this and if there were any good ways around it. 这似乎是一个缺点,所以我想知道是否有人知道这一点以及是否有任何好的方法。 I realise I could cache a reference to the conext in a local variable, but this doesn't seem great. 我意识到我可以在局部变量中缓存对conext的引用,但这看起来不太好。

Update 更新

One approach that works is 一种有效的方法是

            public async Task TestAsync()
    {
        WebOperationContext ctx = WebOperationContext.Current;

        Task t = new Task(()=>Thread.Sleep(10000));

        t.Start();

        await t;

        //ctx is set        
    }

and also, as others have hinted at, I could do this 而且,正如其他人所暗示的那样,我可以做到这一点

        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");
    }

What would be the implications in terms of performance and thread safety of each? 每个的性能和线程安全性会产生什么影响?

I've heard the WCF team is considering solutions for OperationContext.Current , and I expect they will address WebOperationContext.Current as well. 我听说WCF团队正在考虑OperationContext.Current解决方案,我希望他们也能解决WebOperationContext.Current See this SO post (note that Jon Cole is on the MS WCF team). 看到这篇SO帖子 (注意Jon Cole是MS WCF团队的成员)。

In the meantime, you can capture the value in a variable (which improves testability, and is what I recommend), add it to LogicalCallContext , or install your own SynchronizationContext (which would be tricky since you're hosted in IIS which uses its own SynchronizationContext ). 在此期间,您可以捕获变量中的值(提高可测试性,这是我的建议),将其添加到LogicalCallContext ,或者安装您自己的SynchronizationContext (由于您使用自己的IIS托管在IIS中,这将非常棘手SynchronizationContext )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM