C# 如何调用线程。在Win窗体中加入所有线程

C# 如何调用线程。在Win窗体中加入所有线程,c#,.net,multithreading,winforms,C#,.net,Multithreading,Winforms,我有一个Windows窗体,如下所示。它有多个后台线程,STA等等。我有一个名为myfinalpice()的函数。在调用此方法之前,我需要连接与表单关联的所有线程 如何调用线程。在此处连接所有线程(无论有多少线程) 注意:即使我在将来添加一个新线程,这个调用也应该可以正常工作 代码 public partial class Form1 : Form { int logNumber = 0; public Form1() { InitializeCompon

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

如何调用线程。在此处连接所有线程(无论有多少线程)

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

代码

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++;
        }
    }
}

您可以使用如下所示的任务:

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();

简短回答否。如果你能告诉我你想要实现什么,那就更好了?@SriramSakthivel我正在尝试使用Thread.Join而不是Messagebox来解决这个问题。这是根据参考-跟踪您在
列表中创建的线程
?谁创建了这些线程?为什么不使用
任务
而不是线程?然后,您可以使用.net 4.5中的
ContinueWhenAll
Task.WhenAll
添加continuation