c# - 后台 C# 中的线程

标签 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();
}

最佳答案

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

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

这将使使用 ProgressChanged 事件更新用户界面变得更加容易

关于c# - 后台 C# 中的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4549181/

相关文章:

c# - 在显式结构中将多个 CLR 引用字段相互重叠?

c# - WPF 中的下拉文本区域

c# - UI线程如何知道另一个线程上的数据?

iphone - 应该如何使用dispatch_debug?

c# - 使用 .NET Core 的 Firebase 身份验证 (JWT)

c# - C#显示线程无效的跨线程访问问题

c# - 转换与解析

java - 将函数作为参数传递以在 UI 线程上启动

multithreading - 从线程到另一个共享时间戳

multithreading - 在可单元测试的 MVVM 代码中使用 Dispatcher