how to cancel WCF service call?

醉酒当歌 提交于 2019-12-20 04:12:39

问题


I have a WCF function that is executing long time, so I call the function in UI with backgraundworker... I want to give a feature to cancel the execution, so I abort IComunicationObject, the problem is that Service execution is not stoping, Is there any way to stop Service execution in this case?


回答1:


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.




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/949588/how-to-cancel-wcf-service-call

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