(Assuming a WCF method called "MyFunction")
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.
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).
Thanks!
EDIT:
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:
public void StartValidation(){
WcfClient wcf = new WcfClient();
wcf.IsValidCompleted += new EventHandler<IsValidCompletedEventArgs>(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();
}
}
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?
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();
await using var registration = cancellation.Register(client.Abort);
try
{
await client.CallMyServiceAsync();
} catch (CommunicationObjectAbortedException) {
// This will be called when you are cancelled, or some other fault.
}
}
.Net 4.5
Something similar can be implemented in older .Net frameworks too where CancellationToken is not yet available.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With