I am new to async methods and am kinda confused how async is working so what i want for you to do is review this code and tell me does implementing async like this is meaningless
[Route("/Dev/ForceBufferUpdate")]
public async Task<IActionResult> BufferUpdate()
{
bool isAdministrator = await Task.Run(() => {
return Security.IsAdministrator(Request);
});
if(!isAdministrator)
return View("Error", "You don't have permission!");
await Task.Run(() => {
LimitlessSoft.Buffer.Refresh();
});
return Redirect("/Dev");
}
2 Answers 2
This code is pointless since it creates async state machine while the code you execute is actually synchronous code. So eventually you get a performance penalty for the creation of a state machine but no reward of asynchronous execution.
Consider using async
and await
when you're dealing with IO operations. Usually, such methods already provide asynchronous API. You can spot this as such methods return Task
or Task<T>
-
\$\begingroup\$ What if
Security.IsAdministrator()
takes 3 second to run. Is then using async useful? \$\endgroup\$Aleksa Ristic– Aleksa Ristic2020年08月18日 07:24:50 +00:00Commented Aug 18, 2020 at 7:24 -
\$\begingroup\$ In case you're operating with I/O that would make sense. Otherwise you might consider offloading this operation into
System.Threading.Thread
\$\endgroup\$Bohdan Stupak– Bohdan Stupak2020年08月18日 09:44:08 +00:00Commented Aug 18, 2020 at 9:44
The async/await method isn't really about running parallel code; it is about releasing the current thread instead of having it wait for i/o bound processing.
Imagine 20 people call that end point; on the first call there is a thread of execution create. If Security.IsAdministrator hits a database then this is IO and that calling thread would block until the IO was complete.
Using Task.Run and async/await will not cause the thread to block, the thread gets released to can process the next 19 calls. Once IO is complete another thread, or the same one, picks up the processing.
So I would say it is not meaningless, if the tasks involve IO.