how to cancel WCF service call?

旧时模样 提交于 2019-12-02 05:20:49

You may not need a BackgroundWorker. You can either make the operation IsOneWay, or implement the asynchronous pattern. To prevent threading issues, consider using the SynchronizationContext. Programming WCF Services does a great job at explaining these.

Make a CancelOperation() method which sets some static ManualResetEvent in your service. Check this event in your Operation method frequently. Or it can be CancelOperation(Guid operationId) if your service can process multiple operation calls concurrently.

Simon_Weaver

One important thing to understand if you're using the Async calls is that there's still no way to cancel a request and prevent a response coming back from the service once it's started. It's up to your UI to be intelligent in handling responses to avoid race conditions. Fortunately there's a simple way of doing this.

This example is for searching orders - driven by a UI. Lets assume it may take a few seconds to return results and the user is running two searches back to back.

Therefore if your user runs two searches and the first search returns after the second - you need to make sure you don't display the results of the first search.

   private int _searchRequestID = 0; // need one for each WCF method you call


   // Call our service...
   // The call is made using the overload to the Async method with 'UserToken'.
   // When the call completes we check the ID matches to avoid a nasty
   // race condition
   _searchRequestID = _searchRequestID++;
   client.SearchOrdersCompleted += (s, e) =>
   {
       if (_searchRequestID != (int)e.UserState))
       {
           return; // avoid nasty race condition
       }

       // ok to handle response ...
    }
    client.SearchOrdersAsync(searchMessage, _searchRequestID);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!