What's the best way to cancel an asynchronous WCF request?

Easiest way I know of to do this with a WCF Client and the Task based async pattern is to register an Abort action with the cancellation token

private async Task CallOrAbortMyServiceAsync(CancellationToken cancellation)
{
    var client = new SomeServiceClient();
    cancellation.Register(() => client.Abort());
    try
    {
         await client.CallMyServiceAsync();
    } catch (CommunicationObjectAbortedException) {
          // This will be called when you are cancelled, or some other fault.
    }
}

There is no way to cancel the asynchronous request unless you manually create the asynchronous functions. Considering that you are auto generating your WCF calls that would make it more of a chore. Even then like you said the call does not cancel it will still run it's course. If you still want to have a cancel you just have to make sure the client/UI ignores the results from the call.


.Net 4.5

  1. Every WCF call implementation creates a CancellationTokenSource and stores it in a location accessible to all WCF services. I.e. in single server environments can be in an in memory cache.
  2. CancellationTokenSource.Token is passed to all method calls initiated by WCF method, including calls to databases and network calls where applicable.
  3. The WCF method can have a unique identifier as parameter or can return a unique identifier what is associated with CancellationTokenSource.
  4. When client needs to cancel the operation calls a WCF method and passes in the unique identifier of previous call.
  5. CancellationTokenSource is retrieved using the unique identifier and its Cancel method is invoked. If cancellation token is properly handled the operation started by previous call will soon be cancelled and can either return OperationCanceledException or a CancelFault or some other fault what signals client that call was cancelled.
  6. When client calls cancel at step 4 at the same time can abort the original WCF call. However if clients properly handle OperationCanceledException or CancelFault this isn't needed. OperationCanceledException can even bubble up to an ajax call if original call was started from a web page.

Something similar can be implemented in older .Net frameworks too where CancellationToken is not yet available.