如何取消异步WCF调用? [英] How to cancel an async WCF call?

查看:126
本文介绍了如何取消异步WCF调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试一些时间,以了解如何基于新的.NET 4.5 CancellationToken机制实现WCF呼叫取消。我发现的所有样本都不基于WCF,并且没有跨越服务边界。

I have been trying some time to find out how to implement WCF call cancellation based on the new .NET 4.5 CancellationToken mechanism. All the samples I found are not WCF based, and do not cross the service boundary.

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class MyService : IMyService
{   
    public void LongOperation()
    {
        // do stuff that takes ages...
        // please cancel me!
    }
}



我的客户(桌面应用程序):



使用自动生成的代理:

My Client (Desktop App):

Using an auto generated proxy :

private async void DoLongRunningTaskAsync()
{
    var asyncTask = _myService.LongOperationAsync();
    await asyncTask;
}

如何取消此任务?请提供适用于.NET 4.5+上WCF的具体示例。

How do I cancel this task? Please provide a concrete example applicable to WCF on .NET 4.5+

下面的答案似乎表示出于技术原因是不可能的。因此,想象一下,我将服务设置为 ContextMode = Session ,然后设置一个名为 cancellationPending = true ,此阶段我的原始调用仍在运行,它会定期检查该变量。我仍然无法取消吗?还是不可能吗?如果是,为什么?

The answers below seem to indicate that its impossible for technical reasons. So, imagine, I make my service ContextMode=Session, then set a static variable (in a separate service call) called cancellationPending=true, my original call is still running at this stage, and it periodically checks that variable. Would I still not be able to cancel? would it still be impossible? if so, why?

推荐答案

如前所述。

如果要在客户端取消任务,可以使用扩展方法 Microsoft.VisualStudio.Threading.ThreadingTools> WithCancellation a>

If you want to cancel the Task on client side you can can use the extension method WithCancellation from Microsoft.VisualStudio.Threading.ThreadingTools

它是 Visual Studio SDK ,或者您也可以从 Nuget

It is part of Visual Studio SDK or you can also get it from Nuget.

 CancellationTokenSource ct = new CancellationTokenSource();
 ct.CancelAfter(20000);
 var asyncTask = _myService.LongOperationAsync();
 await asyncTask.WithCancellation(ct.Token);

这篇关于如何取消异步WCF调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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