在 WCF 服务中使用 async/await 时,OperationContext.Current 在第一次等待后为空 [英] OperationContext.Current is null after first await when using async/await in WCF service

查看:19
本文介绍了在 WCF 服务中使用 async/await 时,OperationContext.Current 在第一次等待后为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 .NET 4.5 中使用 async/await 模式在 WCF 中实现一些服务方法.示例服务:

I am using async/await pattern in .NET 4.5 to implement some service methods in WCF. Example service:

合同:

[ServiceContract(Namespace = "http://async.test/")]
public interface IAsyncTest
{
    Task DoSomethingAsync();
}

实施:

MyAsyncService : IAsyncTest
{
    public async Task DoSomethingAsync()
    {
        var context = OperationContext.Current; // context is present

        await Task.Delay(10);

        context = OperationContext.Current; // context is null
    }
}

我遇到的问题是,在第一个 await OperationContext.Current 返回 null 之后,我无法访问 OperationContext.Current.IncomingMessageHeaders.

The problem I am having is that after first await OperationContext.Current returns null and I can't access OperationContext.Current.IncomingMessageHeaders.

在这个简单的例子中,这不是问题,因为我可以在 await 之前捕获上下文.但在实际情况下,OperationContext.Current 是从调用堆栈的深处访问的,我真的不想为了进一步传递上下文而更改大量代码.

In this simple example this is not a problem since I can capture the context before the await. But in the real world case OperationContext.Current is being accessed from deep inside the call stack and I really don't want to change lots of code just to pass the context further.

有没有办法在 await 点之后获取操作上下文,而无需手动将其向下传递堆栈?

Is there a way to get operation context after await point without passing it down the stack manually?

推荐答案

我认为最好的选择是实际捕获它并手动传递它.您可能会发现这提高了代码的可测试性.

I think your best option is to actually capture it and pass it manually. You may find this improves the testability of your code.

也就是说,还有其他几个选择:

That said, there are a couple of other options:

  1. 将其添加到 LogicalCallContext.
  2. 安装您自己的SynchronizationContext,它会在执行Post 时设置OperationContext.Current;这就是 ASP.NET 保留其 HttpContext.Current 的方式.
  3. 安装您自己的 TaskScheduler,它设置 OperationContext.Current.
  1. Add it to the LogicalCallContext.
  2. Install your own SynchronizationContext which will set OperationContext.Current when it does a Post; this is how ASP.NET preserves its HttpContext.Current.
  3. Install your own TaskScheduler which sets OperationContext.Current.

您可能还想在 Microsoft Connect 上提出此问题.

You may also want to raise this issue on Microsoft Connect.

这篇关于在 WCF 服务中使用 async/await 时,OperationContext.Current 在第一次等待后为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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