1

I have a Windows Form as listed below. It has multiple background threads, STA, etc… I have a function named MyFinalPiece(). I need to join all threads that are associated with the form before calling this method.

How can I call the Thread.Join here for all threads (irrespective of how many threads are there)?

Note: Even if I add a new thread in future this call should work without break.

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++;
        }
    }
}
pravprab
  • 2,301
  • 3
  • 26
  • 43
LCJ
  • 22,196
  • 67
  • 260
  • 418
  • 1
    Short answer **no**. It will be better if you can tell what are you trying to achieve? – Sriram Sakthivel Apr 09 '14 at 03:49
  • @SriramSakthivel I am trying to use Thread.Join instead of Messagebox to resolve this issue http://stackoverflow.com/questions/22794774/how-to-handle-this-thread-issue . This is as per Reference - http://stackoverflow.com/questions/21571598/which-blocking-operations-cause-an-sta-thread-to-pump-com-messages – LCJ Apr 09 '14 at 03:52
  • 2
    Keep track of the threads you create in a `List`? – Blorgbeard Apr 09 '14 at 03:59
  • 1
    Who creates those threads? and why not use `Task` instead of thread? You can then add continuation using `ContinueWhenAll` or `Task.WhenAll` in .net 4.5 – Sriram Sakthivel Apr 09 '14 at 04:01

1 Answers1

0

May be you can use tasks as shown:

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();
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Palak.Maheria
  • 1,497
  • 2
  • 15
  • 32