问题
I am running into confusing behavior related to async code registered on an ASP.NET page with RegisterAsyncTask, ViewState, and checkboxes, and I need to know exactly when these async-tasks run relative to when ViewState is saved.
I have a few checkboxes inside an ASP:PlaceHolder control. I am reading a record and populating the checkboxes, then I make the PlaceHolder visible.
If all this is synchronous - maybe within Page_Load - all is well.
If this is registered as an async task the following happens:
- The checkboxes get populated.
- The Placeholder is visible.
- On postback, checkboxes cannot be UNCHECKED. That is, if they were initially checked they retain their checked status even if the user unchecked them. It seems like the checkboxes revert back to their initial values. If a checkbox is checked on the client, that makes it! Unchecking doesn't.
This doesn't seem to be a problem with textboxes. I haven't tried other widgets.
I can 'correct' this problem by setting the PlaceHolder to be visible BEFORE I register the async task. I think this is similar to my other question about Grid visiblity:
asp:DataGrid visibility with async?
It's turning out to be very difficult and resulting in confusing code as I try to pull all the visiblity-rules out of async methods.
I see from the ASP.NET page lifecycle that gets saved sometime before OnPreRender. I also think RegisterAsyncTask'd code gets run about the same time. What order does this happen in? If ViewState is saved before my code runs I'm sunk!
Edit: I found some more detail but it is still confusing: Halfway down this page: http://www.asp.net/web-forms/overview/performance-and-caching/using-asynchronous-methods-in-aspnet-45 it says
"Methods hooked up with RegisterAsyncTask will run immediately after PreRender."
This page: https://msdn.microsoft.com/en-us/library/ms178472(v=vs.85).aspx details the PreRender and SaveStateComplete events but doesn't mention RegisterAsyncTask. I need to experiment to see if its shoe-horned between them.
回答1:
The ExecuteRegisteredAsyncTasks gives you some more control in when the tasks are being started.
The
ExecuteRegisteredAsyncTasks
method is automatically called at the point in the page processing when any registered asynchronous tasks, if they exist, are invoked for a non-asynchronous page. This automatic call toExecuteRegisteredAsyncTasks
occurs just before the PreRenderComplete event.
From PreRenderComplete documentation:
This is the last event raised before the page's view state is saved.
来源:https://stackoverflow.com/questions/31567515/when-exactly-do-page-registerasynctasks-get-called