c# - 异步 WCF 方法 WebOperationContext 在等待后为 null

标签 c# wcf async-await

在下面的示例中,该方法公开为 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/

相关文章:

c# - MonoDroid SurfaceView

c# - 如何将 rtf 字符串提供给 richtextbox 控件

asp.net - 如何提高 .net wcf 服务的性能

wcf - MVVM 与 WCF 数据服务

c# - 使用 async/await 将现有的 C# 同步方法转换为异步方法?

asynchronous - 在 Google Apps 脚本上运行异步函数

c# - 尝试在网站上获取歌曲列表不起作用

c# - 在 GridControl.View 中绑定(bind) IsEnabled 属性

Silverlight 自动在 http 和 https 之间选择安全传输模式

javascript - 为什么在函数中定义分块对象(由于缺乏更好的术语)是有效的 JavaScript?