且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

等待方法完成

更新时间:2022-10-30 18:57:55

除非您使用多个线程,否则在方法完全完成之前,不会在调用代码中继续执行.>

如果您正在使用多个线程,则实际上取决于您如何启动任务.例如,您可能正在使用异步委托执行( foo.BeginInvoke(...))或任务并行库,或者只是创建一个新线程.每种方法都有其自己的等待方式,直到任务/线程完成为止.请给我们更多信息,我们可以为您提供更多帮助,但是选项可能包括:

  • 在委托上调用 EndInvoke ,传入 BeginInvoke
  • 返回的 IAsyncResult
  • 调用 Task.Wait (可选,有超时)
  • 调用 Thread.Join (可以选择超时)

How can I wait for a method to finish using C#?

Unless you're using multiple threads, execution won't continue in the calling code until the method has completed anyway.

If you are using multiple threads, it really depends on how you're launching the task. For example, you could be using asynchronous delegate execution (foo.BeginInvoke(...)) or the Task Parallel Library, or simply creating a new thread. Each approach has its own way of waiting until the task/thread has completed. Please give us more information and we can help you more, but options may include:

  • Calling EndInvoke on the delegate, passing in the IAsyncResult returned by BeginInvoke
  • Calling Task.Wait (optionally with a timeout)
  • Calling Thread.Join (optionally with a timeout)