简体   繁体   English

等待方法完成

[英]Wait for method to finish

我如何等待方法完成使用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. 例如,您可以使用异步委托执行( foo.BeginInvoke(...) )或任务并行库,或者只是创建一个新线程。 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 在委托上调用EndInvoke ,传入BeginInvoke返回的IAsyncResult
  • Calling Task.Wait (optionally with a timeout) 调用Task.Wait (可选择超时)
  • Calling Thread.Join (optionally with a timeout) 调用Thread.Join (可选择超时)
  1. Call the method. 调用方法。
  2. Wait for it to finish. 等待它完成。

Note : Only works for blocking calls. 注意 :仅适用于阻止呼叫。

I assume you are asking how to wait for a Code executing on another Thread in your main Thread . 我假设您正在询问如何在主线程中的另一个线程上等待代码执行。 For that purpose Thread.Join() method will do what you want. 为此, Thread.Join()方法将执行您想要的操作。

(A nice tutorial on how to do Multithreading .) (关于如何进行多线程的一个很好的教程。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM