问题描述
我使用异步/等待在.NET 4.5模式来实现一些服务方法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
}
}
我遇到的问题是,经过第一个等待
OperationContext.Current
返回空
,我无法访问 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
.
在这个简单的例子,这不是一个问题,因为我可以捕捉在计谋
的范围内。但在现实世界的情况下 OperationContext.Current
从调用堆栈深处被访问,我真的不想改变很多code只是通过范围内进一步。
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.
有没有办法在来获取操作方面等待
点,而无需手动传递下来的堆?
Is there a way to get operation context after await
point without passing it down the stack manually?
推荐答案
我觉得你最好的选择是真正抓住它,然后手动将它传递。您可能会发现这提高了你的code中的可测性。
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:
- 将其添加到
LogicalCallContext
。 - 在安装自己的
的SynchronizationContext
这将设置OperationContext.Current
时,它做了发布
;这是怎么了ASP.NET preserves其HttpContext.Current
。 - 在安装自己的
的TaskScheduler
这台OperationContext.Current
。
- Add it to the
LogicalCallContext
. - Install your own
SynchronizationContext
which will setOperationContext.Current
when it does aPost
; this is how ASP.NET preserves itsHttpContext.Current
. - Install your own
TaskScheduler
which setsOperationContext.Current
.
您可能还需要在Microsoft Connect上提出这个问题。
You may also want to raise this issue on Microsoft Connect.
这篇关于OperationContext.Current是采用异步时,首先计谋后空/等待在WCF服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!