Skip to content

max-ieremenko/ServiceModel.Cancellation

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ServiceModel.Cancellation library for .Net

Support of CancellationToken for WCF. Allows to propagate notifications from CancellationToken from client to service side.

Version

Supported platforms

.NET Framework 4.5.2 or higher.

Service-side

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

Client-side

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

Todo list to setup your code and environment

Service-side

  • 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

Client-side

  • each client channel has to be pre-configured to support cancellation
  • to pass cancellation requests to service CancellationContractClient will be used by default

Examples

  • CodeConfiguration demonstrates how to configure ServiceModel.Cancellation from code
  • FileConfiguration demonstrates how to configure ServiceModel.Cancellation from application configuration file.

License

This tool is distributed under the MIT license.