So here is my problem with my Windows Phone application.
I have Page 1 that can navigate to Page 2. In Page 2 OnNavigateTo I make a async call.
This seems ok the first time I run the application, the async call creates a new worker thread and does work for me which is cool.
But I realize that if I go back to Page 1 and re-invoke Page 2 the problem appears: Now I have a new worker thread from the async call while the old one was not terminated. So there is a race between the two worker threads and cause a problem to my application.
I don’t have direct control to the threads since they are implicitly created by async methods.
So in this case, anyone has suggestion on how to deal with it or is there a common pattern of dealing with this issue?
It depends on how you’re issuing the async request. If you’re using say,
WebClientto do something likeDownloadStringAsyncyou’ll see that yourWebClientinstance has a methodCancelAsyncthat will set the cancelled property in yourCompletedevent handler totrue. Just callCancelAsyncwhen you leave your page and test for this in your handler and you should be good.If you don’t have
CancelAsyncyou can pass in aUserStateobject that has aCancelledproperty to emulate the behaviour (set it to true when you leave and test in your handler).