Support of CancellationToken for WCF. Allows to propagate notifications from CancellationToken from client to service side.
.NET Framework 4.5.2 or higher.
using CancellationTokenProxy = ServiceModel.Cancellation.CancellationTokenProxy;
[ServiceContract]
[UseCancellation] // enable cancellation support for service
public class DemoService
{
// accept request with CancellationSourceToken
[OperationContract]
public async Task<OperationResult> RunOperationAsync(TimeSpan delay, CancellationTokenProxy token)
{
var timer = Stopwatch.StartNew();
try
{
await Task.Delay(delay, token);
}
catch (TaskCanceledException ex) when (ex.CancellationToken == token)
{
}
return new OperationResult
{
ExecutionTime = timer.Elapsed,
IsCanceled = token.IsCancellationRequested
};
}
}
using (var cancellationSource = new CancellationTokenSource())
using (var clientFactory = new ChannelFactory<IDemoService>())
{
// enable cancellation support for client
clientFactory.UseCancellation();
// cancel request after 1 second
cancellationSource.CancelAfter(TimeSpan.FromSeconds(1));
var client = clientFactory.CreateChannel();
// pass CancellationSourceToken to service
var response = await client.RunOperationAsync(
TimeSpan.FromSeconds(5),
cancellationSource.Token);
Console.WriteLine("ExecutionTime: {0}", response.ExecutionTime);
Console.WriteLine("IsCanceled: {0}", response.IsCanceled);
}
- each service has to be pre-configured to support cancellation
- your environment has to host entry point (see CancellationContractService)) to accept cancellation requests from client
- each client channel has to be pre-configured to support cancellation
- to pass cancellation requests to service CancellationContractClient will be used by default
- CodeConfiguration demonstrates how to configure ServiceModel.Cancellation from code
- FileConfiguration demonstrates how to configure ServiceModel.Cancellation from application configuration file.
This tool is distributed under the MIT license.