0

I want to use CancellationToken in one of async tasks in my WCF service. the implementation is as follows:

 [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;
    }
}

the WCF interface:

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

I get this error : System.NotSupportedException: 'The use of 'System.Threading.CancellationToken' on the task-based asynchronous method is not supported.'

what should I do and how can I use cancellation token inside my async task?

Milad
  • 23
  • 8

1 Answers1

0

There is no way to cross service boundaries and cancel on the server side.

You can do this using WCF client-side and task-based async patterns by registering an Abort action with a cancellation token Or use the extension method WithCancellation of Microsoft.VisualStudio.Threading.ThreadingTools.

For details, see the link below:
How to cancel an async WCF call?
What's the best way to cancel an asynchronous WCF request?
How to use the CancellationToken property?

Lan Huang
  • 613
  • 2
  • 5