简体   繁体   中英

Async method in an ASP.NET Web Form

I have to use a third-party library in a ASP.NET web forms app.

The third-party method I have to use is an async one.

Since I have to call it in a page click event handler, I have 2 options:

  1. Declare every page that has to use this method as <%@ Page Async="true"... %>
  2. Invoke the method synchronously.

FIRST QUESTION

Does it make sense to declare all the website pages async only for this method (potentially can be invoked on every page)?

SECOND QUESTION

The second question is about invoking the async method synchronously.

Having to invoke the following method

async Task<bool> MyMethodAsync()
{
    ...
}

Which is the difference between the next 3 invocations?

Task.Run(async () => await MyMethodAsync()).GetAwaiter().GetResult();
Task.Run(() => MyMethodAsync()).GetAwaiter().GetResult();
MyMethodAsync().GetAwaiter().GetResult();

I cannot see any difference during execution…

Thanks!

Task.Run(async () => await MyMethodAsync()).GetAwaiter().GetResult();

This starts a task to run on a threadpool thread that runs the method asynchronously. Then the main thread sits there and waits for the threadpool thread task to finish.

Task.Run(() => MyMethodAsync()).GetAwaiter().GetResult();

This is the same as above, but the main function "continues" before the method fully completes.

MyMethodAsync().GetAwaiter().GetResult();

This at least avoids using an extra thread to stall the main thread anyway.

Edit: I didn't see this question:

Does it make sense to declare all the website pages async only for this method (potentially can be invoked on every page)?

Depends what kind of async . If they'd still return void, you're gaining nothing, you're just breaking your code base. If you're returning an actual Task , then sure. In fact that's how ASP.Net Core works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM