异步WCF方法WebOperationContext是后空的await [英] async WCF method WebOperationContext is null after await

查看:314
本文介绍了异步WCF方法WebOperationContext是后空的await的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的例子中,该方法公开为WCF服务操作,服务在IIS托管。
在进入功能如预期的那样WebOperationContext.Current设置。中的await完成后等待,然而,WebOperationContext.Current设置为null。

In the following example, the method is exposed as a WCF service operation and the service is hosted in IIS. On entry into the function the WebOperationContext.Current is set as expected. After the await has finished waiting, however, the WebOperationContext.Current is set to 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的引用,但这似乎并不大。

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.

更新

一种方法,工程是

            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?

推荐答案

我听说WCF团队正在考虑 OperationContext.Current 解决方案,我希望他们会地址 WebOperationContext.Current 为好。见<一href=\"http://stackoverflow.com/questions/12797091/operationcontext-current-is-null-after-first-await-when-using-async-await-in-wcf\">this SO帖子(注意,乔恩·科尔是在MS WCF小组)。

I've heard the WCF team is considering solutions for OperationContext.Current, and I expect they will address WebOperationContext.Current as well. See this SO post (note that Jon Cole is on the MS WCF team).

在此期间,你可以捕捉变量中的值(从而提高可测试性,而这也正是我推荐),将其添加到 LogicalCallContext ,或安装自己的的SynchronizationContext (因为你的IIS它使用托管这将是棘手自己的的SynchronizationContext )。

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).

这篇关于异步WCF方法WebOperationContext是后空的await的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆