【问题标题】:How to call Thread.Join for all threads in Win Forms如何为 Winforms 中的所有线程调用 Thread.Join
【发布时间】:2014-04-09 03:40:00
【问题描述】:

我有一个如下所列的 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++;
        }
    }
}

【问题讨论】:

  • 简答。如果你能说出你想要达到的目标会更好?
  • @SriramSakthivel 我正在尝试使用 Thread.Join 而不是 Messagebox 来解决此问题 stackoverflow.com/questions/22794774/…。这是根据参考 - stackoverflow.com/questions/21571598/…
  • 跟踪您在List<Thread>中创建的线程?
  • 谁创建了这些线程?为什么不使用Task 而不是线程?然后,您可以在 .net 4.5 中使用 ContinueWhenAllTask.WhenAll 添加延续

标签: c# .net multithreading winforms


【解决方案1】:

也许你可以使用如图所示的任务:

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

【讨论】:

    猜你喜欢
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-07
    • 1970-01-01
    • 2018-05-30
    相关资源
    最近更新 更多