0

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.

  • 1
    Sure looks asynchronous to me. You might consider rewriting that though to move the bulk of the work out of main and into an async helper method. – Eric Lippert Jan 09 '17 at 18:49
  • the main function is synchronous because of the .Wait(). However since main processes 2 tasks synchronously you can call this parallel processing. I'm very curious to know why the nomenclature of your program is so important. – Guillaume CR Jan 09 '17 at 18:53
  • Who is forcing you to commit to one definition or another? Does the program *work*? Is it demonstrably correct? Aren't those better questions to ask than to try to classify the program? And if you do need to classify your program as either synchronous or asynchronous, I'd rather see what specific rules your problem setter has defined. – Damien_The_Unbeliever Jan 09 '17 at 18:55
  • On a side note, I'm very jealous that you got an answer from @EricLippert himself. Congratulations! – Guillaume CR Jan 09 '17 at 18:55

2 Answers2

3

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

Community
  • 1
  • 1
0

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.

John Wu
  • 50,556
  • 8
  • 44
  • 80