【问题标题】:System.NotSupportedException: 'The use of 'System.Threading.CancellationToken' on the task-based asynchronous method is not supported.'System.NotSupportedException:'不支持在基于任务的异步方法上使用'System.Threading.CancellationToken'。'
【发布时间】:2022-02-07 15:20:54
【问题描述】:

我想在我的 WCF 服务中的一项异步任务中使用 CancellationToken。实现如下:

 [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Reentrant)]
public partial class MyService: IMyService
{
     private void Initialize()
    {
        _serviceHost = new ServiceHost(this, new Uri[] { new Uri("net.pipe://localhost") });
        var binding = new NetNamedPipeBinding();

        _serviceHost.AddServiceEndpoint(typeof(IMyService), binding, "MyService");
        var behavior = _serviceHost.Description.Behaviors.Find<ServiceBehaviorAttribute>();
        behavior.InstanceContextMode = InstanceContextMode.Single;
        _serviceHost.Open(); // I get error on this line
    }

    public async Task<List<object>> DoSomeWorkAsync(CancellationToken ct = default(CancellationToken))
    {
        //do some work
        ...

        var list = await SomeAwaitableTask(ct);
        return list;
    }
}

WCF 接口:

[ServiceContract(CallbackContract = typeof(IClientCallback))]
public interface IMyService
{
    [OperationContract]
    [FaultContract(typeof(ServiceExceptionDTO))]
    Task<List<object>> DoSomeWorkAsync(CancellationToken ct = default(CancellationToken));
}

我收到此错误: System.NotSupportedException: '不支持在基于任务的异步方法上使用'System.Threading.CancellationToken'。'

我应该怎么做以及如何在我的异步任务中使用取消令牌?

【问题讨论】:

    标签: c# wcf async-await windows-services


    【解决方案1】:

    无法跨越服务边界并在服务器端取消。

    您可以使用 WCF 客户端和基于任务的异步模式通过注册带有取消令牌的 Abort 操作来执行此操作 或者使用 Microsoft.VisualStudio.Threading.ThreadingTools 的扩展方法 WithCancellation。

    详情见以下链接:
    How to cancel an async WCF call?
    What's the best way to cancel an asynchronous WCF request?
    How to use the CancellationToken property?

    【讨论】:

      猜你喜欢
      • 2012-01-04
      • 2014-10-30
      • 2016-01-31
      • 2013-03-30
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 2015-03-20
      相关资源
      最近更新 更多