Task.Wait synchronously blocks the current thread until a Task completes. It suits legacy synchronous code that must consume an API offering only a Task-based asynchronous method, but it is inefficient, can cause deadlocks, and should be a last resort. section 3.2.3
After completion, Task.Wait behaves as follows:
- Returns immediately when the task completed successfully. section 3.2.4
- Throws when the task was canceled or faulted; fault details are represented by AggregateException and its InnerExceptions collection. section 3.2.4
- Allows status inspection through IsFaulted, IsCanceled, and IsCompletedSuccessfully before deciding how to handle the result. section 3.2.4
Synchronous consumption of an asynchronous file API
var readCompleted = File.ReadAllBytesAsync("example.bin"); readCompleted.Wait(); // use the completed data through the task's result section 3.2.3
var readCompleted = File.ReadAllBytesAsync("example.bin");
var bytes = readCompleted.Result; #1
// do something with bytes
Compare Task<T>.Result with Task.Wait when adapting asynchronous file reading to synchronous code. section 3.2.3
