Reputation: 16723
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.
Upvotes: 3
Views: 136
Reputation: 50672
The commonly made mistake is that await blocks. It doesn't.
The current thread returns immediately and the remainder of the function is registered to be executed when the asynchronous Task completes.
Upvotes: 0
Reputation: 1500065
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.
Upvotes: 6