Search code examples
c#wcfasync-awaittask-parallel-library

Setting a TaskCompletionSource to Cancel state faults WCF channel


I have an async WCF operation which I am cancelling on a certain condition (see below). However, I am getting Faulted event at client side after this. I also have a FaultHandler configured at Server side but the call does not go to HandleError or ProvideFault.

Is this the default behavior of Task based WCF operation? Shouldn't we get a OperationCanceledException at client side?

Sample Code

Operation:

Task<MyResult> CalculateResultAsync(SomeParameter parameter);

Service Side:

Task<MyResult> CalculateResultAsync(SomeParameter parameter)
{
    TaskCompletionSource<MyResult> tcs = new TaskCompletionSource<MyResult>();

    Task.Run(() => {
        //do something
        //based on some condition cancel tcs
        tcs.SetCanceled();
    });

    return tcs.Task;
}

Solution

  • The implementation of the service does not change the SOAP protocol.

    If the service faulted (cancelled), than the client receives a fault.

    Besides that, using Task.Run on server code is usually a bad practice because it will be trading one thread pool thread for another and back again.