Mittens Romney
Mittens Romney

Reputation: 3

Would this program be considered asynchronous?

Let's say I have a simple program like

public static main(string[] args)
{
    Task<int> hotTask = Task<int>.Run(() => SomethingThatRunsInBackgroundAndReturnsAnInt());
    DoIndependentWork();
    hotTask.Wait(); 
    Console.WriteLine(hotTask.Result);
}

Would this technically be "synchronous" despite the fact that it runs a background thread that doesn't need to be finished before the next unit of work (DoIndependentWork()) is started and finished? I can't find a very good technical definition anywhere on the internet.

Upvotes: 0

Views: 77

Answers (2)

John Wu
John Wu

Reputation: 52240

Yeah, sort of, but technically, no

Maybe this is a nit, but I would state that your program uses asynchronous operations, but is not itself asynchronous. This is because the program's main method will not return until the program has finished processing.

When we talk about an asynchronous method, we are not talking about a method that uses multiple threads; we are talking about a method that returns nearly immediately and before the work is done. Similarly, for a program, we are not talking about a program that uses multiple threads, but a program that returns nearly immediately and before the work is done.

An example of an asynchronous program would be a Windows Service. The operating system will call the service's OnStart method, which returns nearly immediately. Meanwhile the service maintains another thread which does the main work asynchronously.

Your program, therefore, does not meet the definition.

Upvotes: 0

Maciej Długoszek
Maciej Długoszek

Reputation: 437

According to this : Asynchronous vs synchronous execution, what does it really mean?

When you execute something synchronously, you wait for it to finish before moving on to another task. When you execute something asynchronously, you can move on to another task before it finishes.

In your case you do SomethingThatRunsInBackgroundAndReturnsAnInt() and you do not wait for the task to end, but rather execute another function, which means that it is an asynchronous program

Upvotes: 3

Related Questions