我有一个Windows窗体,如下所示。它有多个后台线程,STA
等...我有一个名为MyFinalPiece()
的函数。在调用此方法之前,我需要连接与表单关联的所有线程。
如何在线调用所有线程的Thread.Join(无论有多少线程)?
注意:即使我将来添加一个新线程,这个调用也应该没有中断。
CODE
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++;
}
}
}
答案 0 :(得分:0)
可以使用如下所示的任务:
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();