title: What's the best way to cancel an asynchronous WCF request?
body: <p>(Assuming a WCF method called "MyFunction")</p>
  
  <p>Currently, to support canceling a WCF request, I'm using the BeginMyFunction/EndMyFunction methods generated by svcutil (and handling an isCanceled flag when dispatching the results to the main thread). I'd like to use the MyFunctionAsync method (and hooking into MyFunctionAsyncCompleted event instead) for async calls instead of Begin/End. </p>
  
  <p>What is the best/supported way to handle canceling WCF requests if using MyFunctionAsyncCompleted, and still ensuring that the event doesn't get fired on a page that's no longer loaded (i.e. page navigation within a frame). </p>
  
  <p>Thanks!</p>
  
  <p><strong>EDIT:</strong> </p>
  
  <p>I've decided that I want to create my WcfClient object on a per-call basis (as opposed to per-WPF-Page or per-Application), so here's what I've come up with:</p>
  
  <pre><code>public void StartValidation(){
      WcfClient wcf = new WcfClient();
      wcf.IsValidCompleted += new EventHandler&lt;IsValidCompletedEventArgs&gt;(wcf_IsValidCompleted);
      //pass the WcfClient object as the userState parameter so it can be closed later
      wcf.IsValidAsync(TextBox.Text, wcf);  
  }
  
  void wcf_IsValidCompleted(object sender, IsValidCompletedEventArgs e) {
      if(!m_IsCanceled){
          //Update the UI
          //m_IsCanceled is set to true when the page unload event is fired
      }
      //Close the connection
      if (e.UserState is WcfClient) {
          ((WcfClient)e.UserState).Close();
      }
  }
  </code></pre>
  
  <p>I'm finding it difficult to figure out what the recommended way to accomplish what I've just implemented is. Is this fine as-is, or are there pitfalls/edge cases that I need to worry about? What's the golden standard when it comes to properly canceling a WCF call?</p>