背景中的线程C#

use*_*921 1 c# multithreading

我想在程序运行期间显示进度条.当用户单击button1时,此功能正在运行.我使用了在后台运行的tread,但在我的程序中,这个线程在程序完成运行此函数后运行.我怎么修理它?

private void button1_Click(object sender, EventArgs e)
{
    pr(sender,e);
}

public void pr(object sender, EventArgs e)
{
    if (... == DialogResult.OK)
    {
        if (...)
        {
            Thread wa = new Thread(new ThreadStart(this.lad));
            wa.IsBackground = true;

            timer1.Interval = 500;
            timer1.Start();
            wa.Start();

            if (... == DialogResult.OK)
            {//the rest of the function}
        }
    }
}

private void lad()
{
    int war = 10;

    if (this.progressBar1.InvokeRequired)
    {
        progressBar1.Invoke((Del)delegate
        {
            for (int i = 1; i <=10; i++)
            {
                this.progressBar1.Value = this.progressBar1.Value + war;
            }
        });
    }
    if (progressBar1.Value == progressBar1.Maximum)
    {
        timer1.Stop();
        MessageBox.Show("files saved");
    }
}

private void timer1_Tick(object sender, EventArgs e)
{
    ladowanie_paska();
}
Run Code Online (Sandbox Code Playgroud)

小智 7

我强烈建议重写代码以使用BackgroundWorker类;

http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx

这样可以更轻松地使用ProgressChanged事件更新用户界面