如何为Win Forms中的所有线程调用Thread.Join

本文关键字:线程 调用 Thread Join Win Forms | 更新日期: 2023-09-27 17:57:41

我有一个Windows窗体,如下所示。它有多个后台线程,STA等等…我有一个名为MyFinalPiece()的函数。在调用此方法之前,我需要连接与表单关联的所有线程。

如何为所有线程调用Thread.Join(无论有多少线程)?

注意:即使我将来添加了一个新线程,这个调用也应该可以正常工作。

代码

public partial class Form1 : Form
{
    int logNumber = 0;
    public Form1()
    {
        InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        WriteLogFunction("**");
        //......Other threads
        //..Main thread logic
        //All threads should have been completed before this.
        MyFinalPiece();
    }
    private void MyFinalPiece()
    {
    }
    private void WriteLogFunction(string strMessage)
    {
        string fileName = "MYLog_" + DateTime.Now.ToString("yyyyMMMMdd");
        fileName = fileName + ".txt";
        using (StreamWriter w = File.AppendText(fileName))
        {
            w.WriteLine("'r'n{0} ..... {1} + {2}ms >>> {3}  ", logNumber.ToString(), DateTime.Now.ToLongTimeString(), DateTime.Now.Millisecond.ToString(), strMessage);
            logNumber++;
        }
    }
}

如何为Win Forms中的所有线程调用Thread.Join

您可以使用如下任务:

WriteLogFunction("**");
//......Other threads
var task1 = Task.Run(() => this.SomeOtherThread1());
var task2 = Task.Run(() => this.SomeOtherThread2());
//..Main thread logic
Task.WaitAll(task1, task2);
//All threads should have been completed before this.

MyFinalPiece();