A common task I have to do for a site I work on is the following:
- Download data from some third-party API
- Process the data in some fashion
- Display the results on the page
I was initially using WebClient.DownloadStringAsync and doing my processing on the result. However I was finding that DownloadStringAsync was not respecting the AsyncTimeout parameter, which I sort of expected once I did a little reading about how this works.
I ended up adapting the code from the example on how to use PageAsyncTask to use DownloadString() there – please note, it’s the synchronous version. This is probably okay, because the task is now asynchronous. The tasks now properly time out and I can get the data by PreRender() time – and I can easily genericize this and put it on any page I need this functionality.
However I’m just worried it’s not ‘clean’. The page isn’t notified when the task is done like the DownloadStringAsync method would do – I just have to scoop the results (stored in a field in the class) up at the end in my PreRender event.
Is there any way to get the Webclient’s Async methods to work with RegisterPageTask, or is a helper class the best I can do?
Notes: No MVC – this is vanilla asp.net 4.0.
If you want an event handler on your Page called when the async task completes, you need only hook one up. To expand on the MSDN “how to” article you linked:
public event EventHandler Finished;if (Finished != null){
Finished(this, EventArgs.Empty);
}
mytask.Finished += new EventHandler(mytask_Finished);Regarding ExecuteRegisteredAsyncTasks() being a blocking call, that’s based only on my experience. It’s not documented explicitly as such in the MSDN – http://msdn.microsoft.com/en-us/library/system.web.ui.page.executeregisteredasynctasks.aspx
That said, it wouldn’t be all that practical for it be anything BUT a blocking call, given that it doesn’t return a WaitHandle or similar. If it didn’t block the pipeline, the Page would render and be returned to the client before the async task(s) completed, making it a little difficult to get the results of the task back to the client.