Multi-threaded programming allows multiple tasks to be performed simultaneously. When multiple threads are running simultaneously with the main UI thread, their execution needs to be synchronized. One way is to wait for the thread to complete before continuing execution.
Consider the following code snippet:
<code class="language-csharp">public void StartTheActions() { Thread t1 = new Thread(new ThreadStart(action1)); t1.Start(); // 在启动t2之前等待t1完成。 // 创建一个用作通知机制的事件。 }</code>
To wait for another thread to finish, you can do a few things:
<code class="language-csharp">t1.Join();</code>
This method blocks the current thread until the specified thread completes its execution.
<code class="language-csharp">ManualResetEvent waitEvent = new ManualResetEvent(false); // 启动线程并传递等待事件。 Thread t1 = new Thread(() => { action1(); waitEvent.Set(); }); t1.Start(); // 等待线程完成。 waitEvent.WaitOne();</code>
<code class="language-csharp">public event EventHandler ThreadDone; // 启动线程并添加事件处理程序。 Thread t1 = new Thread(() => { action1(); ThreadDone?.Invoke(this, EventArgs.Empty); }); t1.Start(); // 通过注册事件处理程序来等待线程。 void WaitForThread() { ThreadDone += (sender, args) => { /* 执行操作 */ }; }</code>
<code class="language-csharp">public delegate void ThreadDoneHandler(); // 启动线程并传递用于通知的委托。 Thread t1 = new Thread(() => { action1(); threadDone?.Invoke(); }); t1.Start(); // 通过注册委托来等待线程。 ThreadDoneHandler threadDoneHandler = () => { /* 执行操作 */ }; threadDoneHandler += delegate { threadDoneHandler = null; };</code>
<code class="language-csharp">Task<int> task = Task.Run(() => { return action1(); }); // 等待任务完成。 int result = task.Result;</code>
Which method you choose depends on the specific needs of your application. If you need to block the current thread until another thread completes, Thread.Join()
is probably the most appropriate option. If you don't want to block the thread, you can use other techniques such as events, delegates, or asynchronous operations.
The above is the detailed content of How Can I Wait for a Thread to Complete in .NET?. For more information, please follow other related articles on the PHP Chinese website!