Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you call Wait() on a task multiple times?

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?

like image 778
Mats Isaksson Avatar asked Apr 24 '13 15:04

Mats Isaksson


People also ask

Can you await a task multiple times C#?

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.

How does task Wait work?

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.

What is the difference between wait and await C#?

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.


1 Answers

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.

like image 185
Servy Avatar answered Sep 22 '22 17:09

Servy