简体   繁体   English

后台线程完成后的C#Execute方法

[英]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. 如果我在线程完成之前按下一个按钮,它将打开statusBar并将“openedStatus”设置为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;
}

Using a backgroundWorker fixed my problem: 使用backgroundWorker解决了我的问题:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM