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!
}
}
Using an auto generated proxy :
private async void DoLongRunningTaskAsync()
{
var asyncTask = _myService.LongOperationAsync();
await asyncTask;
}
How do I cancel this task? Please provide a concrete example applicable to WCF on .NET 4.5+
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?
As indicated before. It is impossible to cross service boundary and cancel on server side.
If you want to cancel the Task on client side you can can use the extension method WithCancellation
from Microsoft.VisualStudio.Threading.ThreadingTools
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);