I don´t understand something about async/await:
It is mandatory that an async method must have an await call inside... But if there is an await it is because it is calling another async method, right? So it seems to be an endless chain of async methods with awaits inside calling another async methods.
So is it possible to create a "first" async method, not calling any other async methods inside. Just create an async method because that method does a lot of work that could slow down the system.
An async function is a function declared with the async keyword, and the await keyword is permitted within it. The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.
For methods other than event handlers that don't return a value, you should return a Task instead, because an async method that returns void can't be awaited. Any caller of such a method must continue to completion without waiting for the called async method to finish.
Asynchronous function is a function that returns the type of Future. We put await in front of an asynchronous function to make the subsequence lines waiting for that future's result. We put async before the function body to mark that the function support await .
A method doesn't need an await to be async
, it's the other way around. You can only use await
in an async
method. You may have a method that returns a Task
without it being marked as async
. More here.
IIUC, is about "The Root Of All Async".
So, yes, it is possible to create a "first" async
method. It's simply a method that returns a Task
(or Task<T>
).
There are two types of these tasks: A Delegate Task and a Promise Task.
Task.Run
(most times. Task.StartNew
and new Task(() => {});
are other options) and it has code to run. This is mostly used for offloading work.Task
that doesn't actually execute any code, it's only a mechanism to a. Wait to be notified upon completion by the Task
. b. Signaling completion using the Task
. This is done with TaskCompletionSource
and is mostly used for inherently asynchronous operations (but also for async
synchronization objects) for example: .
private static Task DoAsync()
{
var tcs = new TaskCompletionSource<int>();
new Thread(() =>
{
Thread.Sleep(1000);
tcs.SetResult(5);
}).Start();
return tcs.Task;
}
These tools allow you to create those "roots", but unless you implement an I/O
library (like .Net
's DNS
class) or a synchronization object (like SemaphoreSlim
) yourself, you would rarely use them.
The purpose of the async
keyword is to simply allow the use of await
inside the method, you don't have to call another async
method internally e.g.
public async void WaitForSomething()
{
await Task.Delay(1000);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With