Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a method when thread terminates

I have a form that starts a thread. Now I want the form to auto-close when this thread terminates.

The only solution I found so far is adding a timer to the form and check if thread is alive on every tick. But I want to know if there is a better way to do that?

Currently my code looks more less like this

partial class SyncForm : Form {
    Thread tr;

    public SyncForm()
    {
        InitializeComponent();
    }

    void SyncForm_Load(object sender, EventArgs e)
    {
        thread = new Thread(new ThreadStart(Synchronize));
        thread.IsBackground = true;
        thread.Start();
        threadTimer.Start();
    }

    void threadTimer_Tick(object sender, EventArgs e)
    {
        if (!thread.IsAlive)
        {
            Close();
        }
    }

    void Synchronize()
    {
        // code here
    }
}
like image 837
RaYell Avatar asked Jul 22 '09 09:07

RaYell


3 Answers

The BackgroundWorker class exists for this sort of thread management to save you having to roll your own; it offers a RunWorkerCompleted event which you can just listen for.

like image 185
Steve Gilham Avatar answered Oct 09 '22 23:10

Steve Gilham


Edit to make it call a helper method so it's cleaner.

thread = new Thread(() => { Synchronize(); OnWorkComplete(); });

...

private void OnWorkComplete()
{
    Close();
}
like image 34
Sam Harwell Avatar answered Oct 09 '22 22:10

Sam Harwell


If you have a look at a BackgroundWorker, there is a RunWorkerCompleted event that is called when the worker completes.

For more info on BackgroundWorkers Click Here

Or

You could add a call to a complete function from the Thread once it has finished, and invoke it.

void Synchronize()
{
    //DoWork();
    //FinishedWork();
}

void FinishedWork()
{
if (InvokeRequired == true)
  {
  //Invoke
  }
else
  {
  //Close
  }
}
like image 21
Lloyd Powell Avatar answered Oct 10 '22 00:10

Lloyd Powell