I am coming from a Java development environment and has started to code in C#. I have noticed the 'async/await' pattern in C# that I have never seen in Java. What is it exactly? I have browsed internet for a while and can't find the definite explanation that would clarify my understanding of what it is.
So let's define the following scenario:
first off all the both syntaxes is difference.
Thread Syntax :-
Thread thread = new Thread(() => VoidMethod("","",""));
thread.Start();
https://www.c-sharpcorner.com/blogs/asynchronous-multithreaded-programming-with-example-in-c-sharp
if your using this thread doesn't return any value. while entire request complete.
Task/Task<> Syntax :-
public async Task<int> VoidMethod("","","")
{
await Task.Run(() => VoidMethod("","",""));
return 1;
}
https://www.c-sharpcorner.com/article/async-and-await-in-c-sharp/
if your using this method returns value. while entire request complete.
The best place to start is the docs:
Asynchronous programming with async and await
Than, any blog post by Stephen Toub or Stephen Cleary .
await()
may cause return from the async method, but its execution is not finished, it will be called again some time later. In order to be called later, it gets in the line to some event before return, just like a thread can call to Object.wait()
in Java, which means the thread gets in the line to some event and leaves the processor. Async method leaves the thread, as the thread plays the role of processor for it.
when the event occur, the async method is resumed, that is, it is just invoked again on a next available thread of the thread pool - just like a thread after wait() runs on a next available processor. In order to continue execution not from the start, but from the last place where it returned because of await()
, the information about the state is saved and then used in the form: switch(state) { case 0: goto 0'; case 1: goto 10'; .... }
switch(state) { case 0: goto 0'; case 1: goto 10'; .... }
Note this is bytecode, so goto
can be used. To save the state, we need a field of an object, so async method in fact is not a method but a class, which is instantiated at the place where it is called first time.
Because of direct use of goto
, it is hard or sometimes impossible to code async method in plain C# or Java. But it is always possible to code each part of the async method as a separate method and use that methods as callbacks for the awaited events. Async/await is just another syntax for asynchronous programming, along with callbacks, actors, ComplatableFuture, java.util.concurrent.Flow etc.
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.