gpt4 book ai didi

c# - 使用自定义 header : This OperationContextScope is being disposed out of order 的异步 WCF 客户端调用

转载 作者:IT王子 更新时间:2023-10-29 04:44:30 26 4
gpt4 key购买 nike

我正在从 WinRT 应用调用 WCF 服务。该服务要求为身份验证设置一些 header 。问题是,如果我同时对该服务进行多次调用,我会得到以下异常:

此 OperationContextScope 被乱序处置。

当前代码如下所示:

public async Task<Result> CallServerAsync()
{
var address = new EndpointAddress(url);
var client = new AdminServiceClient(endpointConfig, address);

using (new OperationContextScope(client.InnerChannel))
{
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = GetHeader();

var request = new MyRequest(...);
{
context = context,
};

var result = await client.GetDataFromServerAsync(request);
}
}

我找到了以下评论 from the docs :

Do not use the asynchronous “await” pattern within a OperationContextScope block. When the continuation occurs, it may run on a different thread and OperationContextScope is thread specific. If you need to call “await” for an async call, use it outside of the OperationContextScope block.

看来我显然错误地调用了该服务。但正确的方法是什么?

最佳答案

根据 Microsoft documentation :

Do not use the asynchronous "await" pattern within a OperationContextScope block. When the continuation occurs, it may run on a different thread and OperationContextScope is thread specific. If you need to call "await" for an async call, use it outside of the OperationContextScope block.

所以最简单的正确解决方案是:

Task<ResponseType> task;
using (new OperationContextScope(client.InnerChannel))
{
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = GetHeader();

var request = new MyRequest(...);
{
context = context,
};

task = client.GetDataFromServerAsync(request);
}

var result = await task;

关于c# - 使用自定义 header : This OperationContextScope is being disposed out of order 的异步 WCF 客户端调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13189980/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com