你能调用wait()上的任务多次?你能、任务、wait

2023-09-06 15:50:57 作者:往你心里踹

我要运行一些对象的异步初始化,但某些对象依赖他人进行初始化。然后在需要的所有对象我的应用程序的其他部分继续之前被初始化。

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.

是否有可能再次调用wait()方法就可以了任务,后来调用wait(),或在我的位置时包括一个集合的例子为WaitAll()?

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[ ]>( ) );
      }

还是将那第二个等待()/为WaitAll()会失败?

Or will that second Wait() / WaitAll() fail?

推荐答案

您肯定可以在任务等待两次。你可以等待一个任务多次,只要你想,没有副作用。现在,如果你已经等了一个任务,在同一线程,将已经完成,因此未来等待通话都将只是立即返回,因为其中没有等待对,但他们肯定不会失败或产生不适当的结果。

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.