簡體   English   中英

System.NotSupportedException:'不支持在基於任務的異步方法上使用'System.Threading.CancellationToken'。'

[英]System.NotSupportedException: 'The use of 'System.Threading.CancellationToken' on the task-based asynchronous method is not supported.'

我想在我的 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 客戶端和基於任務的異步模式通過使用取消令牌注冊 Abort 操作來執行此操作,或者使用 Microsoft.VisualStudio.Threading.ThreadingTools 的擴展方法 WithCancellation。

有關詳細信息,請參閱以下鏈接:
如何取消異步 WCF 調用?<\/a>
取消異步 WCF 請求的最佳方法是什么?<\/a>
如何使用 CancellationToken 屬性?<\/a>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM