Asynchronous in C# (1) : Basic Concept

As I am a JS programmer, I will use a lot of javascript to explain how async in C# works. Actually, they are completely different concepts, but it was easier for me to understand this by comparing it with JS. :D

What is asynchronous?

If you are familiar with javascript, this term should be common for you. For some, you may know it as AJAX. Basically, asynchronous operation is an operation where you call a function without waiting for the result.

For example, in jQuery, we have $.ajax which retrieve information from a particular website and proceed to the next statement without waiting for the response. To handle the response, after it finishes retrieving information, it will execute a callback function that we specify as a parameter in $.ajax.

$.ajax({
dataType: “json”,
url: “http://foob.ar",
success: callbackfunction
});

C# version

With the same concept, in C#, we have await operator which tells the compiler that we would like to call that function in asynchronous style.

string result = await WaitAsynchronouslyAsync();

Same as JS, C# will not wait until the operation finish. instead proceeding to the next statement like JS, C# goes back to the caller function and continue working on the next operation of the caller. After the async operation finishes, it, therefore, will continue executing the next operations in that function.

void Foo()
{
Task.Run(GetString());
A();
B();
}
Task<string> async GetString()
{
string result = await WaitAsynchronouslyAsync();
C();
D();
}

In this case, after we reach await WaitAsynchronouslyAsync() and the operation does not finish yet. A(); will be executed. But, sometimes after WaitAsynchronouslyAsync() finishes, the rest operations in GetString function will be executed which is C() and D() in this case. The reason I use the word “sometimes” is because there is no guarantee that they will be executed as soon as the async operation finishes.

Also, there is no guarantee that A(); B(); will be executed before C(); D(); or C(); D(); will be executed before A(); B(); or whatsoever.

For those who write or used to write js may be confused about this, but if you imagine that after await operation is a callback function that would help you a lot easier. Let see following example:

Task<string> async GetString()
{
string result = await WaitAsynchronouslyAsync();
// Start callback function
C();
D();
// End callback function
}

Or, in JS style:


GetString()
{
WaitAsynchronouslyAsync(function(){
C();
D();
});
}

Now, everything would make sense logically. However, this does not imply that underhood C# and JS do the same thing. In fact, they are completely different.

TO BE CONTINUE.

Show your support

Clapping shows how much you appreciated Nash B.’s story.