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

旧街凉风 提交于 2020-01-01 11:02:47

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/16195994/can-you-call-wait-on-a-task-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!