Statement 1. .Wait()
has no return result. It is a void
method, and therefore its result cannot be assigned to a variable.
You can use .Result
which will wait until Task
completes and return a result.
// Both are applicable to simple Tasks:
bool isValid = MyValidationFunction(jsonData).Result;
// does that same as
var task = MyValidationFunction(jsonData);
task.Wait();
bool isValid = task.Result;
However, it is all valid for usual Tasks, but not for async/await functionality, because…
Statement 2. Do not mix up async and .Wait()
– it still blocks the thread, killing the idea of async/await and negating all the performance improvement.
It also causes deadlock in WinForms, WPF, ASP.NET and other environments with SynchronizationContext
.
Read more about it in this Stephen Cleary’s article or in these StackOverflow questions:
- An async/await example that causes a deadlock
- await works but calling task.Result hangs/deadlocks
Simple rule: if you use async, then you use await.
// That's how you do it with async/await:
public async bool GetJsonAndValidate()
{
string jsonData = GetJson();
bool isValid = await MyValidationFunction(jsonData);
}
It will not block the thread and enable asynchronous behavior.