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

前端 未结 5 527
孤城傲影
孤城傲影 2020-12-31 13:57

(Assuming a WCF method called \"MyFunction\")

Currently, to support canceling a WCF request, I\'m using the BeginMyFunction/EndMyFunction methods generated by svcuti

5条回答
  •  长发绾君心
    2020-12-31 14:23

    .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.

提交回复
热议问题