I want to run initializations of some objects asynchronously, but some objects depend on others being initialized. And then all objects need to be initialized before the rest of my application continues.
Is it possible to call Wait() on a task and later call Wait() on it again, or as in my example WaitAll() on a collection where it is included?
Dictionary<String, Task> taskdict = new Dictionary<String, Task>( );
taskdict.Add( "Task1",
Task.Factory.StartNew( ( ) => {
//Do stuff
} ) );
taskdict.Add( "Task2",
Task.Factory.StartNew( ( ) => {
taskdict[ "Task1" ].Wait( );
//Do stuff
} ) );
try {
Task.WaitAll( taskdict.Values.Convert<Task[ ]>( ) );
}
Or will that second Wait() / WaitAll() fail?
The wrapped object may have been reused by another operation. This differs from Task / Task<TResult> , on which you can await multiple times and always get the same result.
Wait is a synchronization method that causes the calling thread to wait until the current task has completed. If the current task has not started execution, the Wait method attempts to remove the task from the scheduler and execute it inline on the current thread.
This is so because 'await' is more formal, as compared to 'wait'. 'Wait' means to pass the time until an anticipated event occurs, whereas 'await' means to wait for something with a hope.
You most certainly can wait on a task twice. You can wait on a task as many times as you want with no negative side effects. Now, if you've already waited on a task in that same thread it will already be done, so the future Wait
calls will all just return immediately as there is nothing to wait for, but they certainly won't fail or otherwise produce inappropriate results.
Note that if a task didn't complete normally and was instead cancelled or couldn't finish as a result of an exception being thrown then calling Wait
will re-throw the exception (each time you call Wait
). If Wait
is throwing exceptions for you, there's a chance that that is the reason.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With