ASP.Net Async Tasks - how to use WebClient.DownloadStringAsync with Page.RegisterAsyncTask

The general task that I have to complete for the site I'm working on is the following:

  • Download data from a third-party API
  • Process data in some way
  • Show results on page

At first I used WebClient.DownloadStringAsync and did my processing on the result. However, I found that DownloadStringAsync does not comply with the AsyncTimeout parameter, which I kind of expected when I read a little about how this works.

I ended up adapting the code using the PageAsyncTask example to use DownloadString () there - note that this is a synchronous version. This is probably good because the task is now asynchronous. Now the tasks are properly exhausted, and I can get the PreRender () time data, and I can easily generalize this and put it on any page, I need this functionality.

However, I'm just worried that this is not "clean." The page will not be notified when the task is completed, as the DownloadStringAsync method does. I just need to scoop up the results (stored in a field in the class) at the end of my PreRender event.

Is there a way to get Webclient Async methods to work with RegisterPageTask or is it a helper class that I can do best?

Notes: No MVC - this is vanilla asp.net 4.0.

+4
source share
1 answer

If you want the event handler on your page to be called when the async task completes, you only need to hook it. To expand the MSDN article "How to", you linked:

  • Change the "SlowTask" class to include an event, for example - public event EventHandler Finished;
  • Call this EventHandler in the "OnEnd" method, for example, if (Finished != null) { Finished(this, EventArgs.Empty); } if (Finished != null) { Finished(this, EventArgs.Empty); }
  • Register an event handler on your page for SlowTask.Finished, for example, mytask.Finished += new EventHandler(mytask_Finished);

Regarding ExecuteRegisteredAsyncTasks (), which is a blocking call based only on my experience. It is not explicitly documented as such on MSDN - http://msdn.microsoft.com/en-us/library/system.web.ui.page.executeregisteredasynctasks.aspx

However, this would not be all that practical if it were something, BUT it was a blocking call, given that it does not return a WaitHandle or the like. If he did not block the pipeline, the page will display and return to the client until the completion of asynchronous tasks, which makes it difficult to return the results of the task to the client.

+1
source

Source: https://habr.com/ru/post/1399867/


All Articles