Async operation immediately awaited

I'm looking at these lines of code from another developer:

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

When I work with async operations, it is to 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 appears that the first example kicks off an async operation and then immediately starts waiting. Is there some value here I don't understand?

Note: this code is in the data access layer of an application, so it isn't interacting with a user interface.

Jon Skeet
people
quotationmark

Is there some value here I don't understand?

Absolutely - it means that although you need the value returned by the operation before you can do any more work, you're not tying up a thread while you're waiting for it. That's particularly important if you're writing a GUI, where tying up the GUI thread basically means freezing the UI.

It sounds like you're focusing on the "doing multiple things in parallel" side of asynchrony, which is important, but far from the only benefit of it.

people

See more on this question at Stackoverflow