Asynchronous work was immediately expected

I am going through these lines of code from another developer:

  bool isValid = await engine.GetTaskByIdAsync(taskId);
  if(isValid )
  ....

      

When I work with operations async

, it should do independent work while the async operation completes:

  Task<bool> task = engine.GetTaskByIdAsync(taskId);

  //Do work that doesn't need the "task" variable

  bool completed = await task;
  if(bool)
  ....

      

It looks like the first example starts an asynchronous operation and immediately starts waiting. Is there any value here I don't understand?

Note: This code is at the Application Data Access layer, so it does not interact with the user interface.

+3


source to share


2 answers


Is there any meaning here I don't understand?

Absolutely - this means that while you need the return value of the operation before you can do any other work, you don't bind the thread while you wait for it. This is especially important if you are writing a GUI where binding the GUI thread basically means freezing the UI.



It looks like you are focusing on the "parallel" side of asynchrony, which is important but far from the only benefit.

+6


source


A common mistake is waiting for blocks. This is not true.



The current thread returns immediately, and the remainder of the function is registered for execution when the asynchronous task completes.

0


source







All Articles