How to cancel an async WCF call?

后端 未结 3 565
隐瞒了意图╮
隐瞒了意图╮ 2020-12-19 20:48

I have been trying some time to find out how to implement WCF call cancellation based on the new .NET 4.5 CancellationToken mechanism. All the samples I found are not WCF ba

3条回答
  •  温柔的废话
    2020-12-19 21:07

    After the edit of the question I see that it is acceptable to have cancellation of logic level. If so, the following algorithm can be tried.

    1) Create a service with InstanceContextMode=InstanceContextMode.PerSession, so that will guarantee you having the same instance of service for serving subsequent requests.

    2) to start new sessions use service operations marked with OperationContract(IsInitiating = True)

    3) create as service member. not static. it will be service state

    CancellationTokenSource ct = new CancellationTokenSource();
    

    4) inside every service method you will have to start new computations inside tasks and put cancellation token as a parameter for this task.

    [ServiceContract(SessionMode = SessionMode.Allowed)]
    public interface ICalculator
    {
       [OperationContract(IsInitiating = True)]
       Bool Begin()
    
       [OperationContract(IsInitiating = false)]
       double Add(double n1, double n2)
    }
    
    [ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)]
    public class CalculatorService : ICalculator
    {
        CancellationTokenSource cts = new CancellationTokenSource();
    
        public double Add(double n1, double n2)
        {
            var cancellationToken = cts.Token;
    
            var t = Task.Factory.StartNew(() => { 
               // here you can do something long
               while(true){
               // and periodically check if task should be cancelled or not
               if(cancellationToken.IsCancellationRequested)
                 throw new OperationCanceledException();
    
               // or same in different words
               cancellationToken.ThrowIfCancellationRequested();
               }
               return n1 + n2;
            }, cancellationToken);
    
            return t.Result;
        }
    
        public Bool Begin(){}
    }
    

    Here is a quick descriptions of WCF sessions.

    All the examples are just from my head, haven't tried if it really work. But you can try.

提交回复
热议问题