My Webforms application which is based on .Net 4.6 has to use the async/await-functionality quite extensively. Because I'm quite new to this async/await topic I read quite a lot of best practices like this or this. But I still have some questions for which I haven't found any clear informations.
Regarding Page-Lifecycle-Events: I know that e.g. for the Page_Load-Event it's best practice to avoid async void-methods and register such methods like this:
protected void Page_Load(object sender, EventArgs e) { PageAsyncTask pageAsyncTask = new PageAsyncTask(SomeAsyncMethod); Page.RegisterAsyncTask(pageAsyncTask); //Method to invoke the registered async-methods immedietly and not after the PreRender-Event Page.ExecuteRegisteredAsyncTasks(); }
My problem is that I want to call the async-method as soon as I registered it and not after the OnPreRender-event. This should be achieved by calling the ExecuteRegisteredAsyncTasks()-method. But in my case this has no effect and the async-method is still invoked after the PreRender-event. But why?
Regarding Control-Events: Is it better to register async-methods the same way I mentioned in the code-example above or can I use the async-void signature like:
protected async void OnClick(object sender, EventArgs e) { await SomeAsyncMethod(); }
I found both examples but no clear informations which is the better solution and why.
Regarding Context and ConfigureAwait, it seems to be best practice to use
await SomeAsyncMethod.ConfigureAwait(false)
for a better performance and where the context is not important and not to use it where the context e.g. when manipulating GUI elements. But in my case it seems to make no difference if I callawait SomeAsyncMethod.ConfigureAwait(false)
in my click-event. I can still manipulate my GUI-elements wihtout any problems. The example which I uses was this:private async void button1_Click(object sender, EventArgs e) { button1.Enabled = false; try { await SomeAsyncMethod().ConfigureAwait(false); } finally { //Manipulating still works even it's another context button1.Enabled = true; } }
So I wonder why the manipulating of the GUI-elements still work and if I really should use ConfigureAwait(false) on every async-method where the context is not important, which is quite tedious. I wonder if this has something to do with the usage of the Ajax-Functionality by Telerik which I use for my Webapplication. But this is just an assumption.
ConfigureAwait(false)
when that method has to call into ASP.NET APIs (such asbutton1.Enabled
). Most APIs work just fine but there are a few that fail, so I just play it safe. - Stephen Cleary