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.
If you have a very intensive method which does a lot of work that could slow down the system, you can call it like this.
Here
IntensiveMethod
is not an async method.Hope it helps.
The purpose of the
async
keyword is to simply allow the use ofawait
inside the method, you don't have to call anotherasync
method internally e.g.Sure, there are indeed ways of creating a
Task
besides using anasync
method.You can use the task constructor (although unless you have a particularly compelling reason to create a task that represents the execution of a delegate that you use before the delegate actually starts executing, you should really avoid doing this. Just use the next option.
You can use an existing method of
Task
to create tasks, such asTask.Run
to represent the execution of a delegate in another thread,Task.WhenAll
to represent the completion of a series of other tasks,Task.FromAsync
to create a task based on a different pattern of asynchronous programming, etc.You can use a
TaskCompletionSource
to create a task that you complete whenever you want, allowing you to turn any inherently asynchronous behavior into aTask
. That inherently asynchronous operation could be an event firing, a callback method being called, etc.First, some clarifications
A method doesn't need an await to be
async
, it's the other way around. You can only useawait
in anasync
method. You may have a method that returns aTask
without it being marked asasync
. More here.Your actual question
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 aTask
(orTask<T>
).There are two types of these tasks: A Delegate Task and a Promise Task.
Task.Run
(most times.Task.StartNew
andnew 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 theTask
. b. Signaling completion using theTask
. This is done withTaskCompletionSource
and is mostly used for inherently asynchronous operations (but also forasync
synchronization objects) for example:.
These tools allow you to create those "roots", but unless you implement an
I/O
library (like.Net
'sDNS
class) or a synchronization object (likeSemaphoreSlim
) yourself, you would rarely use them.