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

前端 未结 5 525
孤城傲影
孤城傲影 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-31 14:44

    Easiest way I know of to do this with a WCF Client and the Task based async pattern is to register an Abort action with the cancellation token

    private async Task CallOrAbortMyServiceAsync(CancellationToken cancellation)
    {
        var client = new SomeServiceClient();
        cancellation.Register(() => client.Abort());
        try
        {
             await client.CallMyServiceAsync();
        } catch (CommunicationObjectAbortedException) {
              // This will be called when you are cancelled, or some other fault.
        }
    }
    

提交回复
热议问题