Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Execute method after background thread finished

I'm using a thread to run a calculation in the background of my program. I start the thread at the start of my program. If I press a button before the thread is finished it will open the statusBar and "openedStatus" is set to true.

This will show the threads current progress and after the thread has finished I would like to execute the last part of my code:

if (openedStatus)
{
    sb.Close();
    validateBeforeSave();
}

This part of the code will throw an exception though because you can't close the statusbar cross-thread.

Now the question is: How can I execute that last part of the code after the thread is finished?

private StatusBar sb = new StatusBar();
private void startVoorraadCalculationThread()
{
    sb.setMaxProgress(data.getProducten().getProductenCopy().Count);
    Thread thread = new Thread(new ThreadStart(this.run));
    thread.Start();
    while (!thread.IsAlive) ;
}

private void run()
{
    for (int i = 0; i < data.getProducten().getProductenCopy().Count; i++ )
    {
        sb.setProgress(i);
        sb.setStatus("Calculating Voorraad: " + (i+1) + "/" + data.getProducten().getProductenCopy().Count);
        data.getProducten().getProductenCopy()[i].getTotaalVoorraad(data.getMaten());
    }
    if (openedStatus)
    {
        sb.Close();
        validateBeforeSave();
    }
    calculationFinished = true;
}
like image 482
Duckdoom5 Avatar asked Oct 03 '22 18:10

Duckdoom5


1 Answers

Using a backgroundWorker fixed my problem:

private void startVoorraadCalculationThread()
{
    sb.setMaxProgress(data.getProducten().getProductenCopy().Count);

    BackgroundWorker bw = new BackgroundWorker();
    bw.DoWork += new DoWorkEventHandler(bw_DoWork);
    bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);

    bw.RunWorkerAsync();
}

private void bw_DoWork(object sender, DoWorkEventArgs e)
{
    for (int i = 0; i < data.getProducten().getProductenCopy().Count; i++)
    {
        sb.setProgress(i);
        sb.setStatus("Calculating Voorraad: " + (i + 1) + "/" + data.getProducten().getProductenCopy().Count);
        data.getProducten().getProductenCopy()[i].getTotaalVoorraad(data.getMaten());
    }
}

private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if (openedStatus)
    {
        sb.Close();
        validateBeforeSave();
    }
    calculationFinished = true;
}
like image 193
Duckdoom5 Avatar answered Oct 12 '22 11:10

Duckdoom5