如何防止窗口形成"挂起"?

时间:2012-08-04 12:20:13

标签: c# winforms hang

  

可能重复:
  C# WinForm Application - UI Hangs during Long-Running Operation

我在C#Windows窗体中创建了一个进度条示例应用程序。

我的应用程序运行良好但是当我尝试移动我的应用程序位置或最小化时,它会“挂起”,直到它的进程不符合。

请帮助:如何阻止我的应用程序“挂起”?

这是我的应用代码:

public partial class ProgressBar : Form
{
    public ProgressBar()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        int value;
        for (value = 0; value != 10000000; value++)
            progressBar1.Value = progressBar1.Value + 1;

        MessageBox.Show("ProgressBar Full", "Done", 
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
        this.Close();
    }

    private void ProgressBar_Load(object sender, EventArgs e)
    {
        progressBar1.Maximum = 10000000;
    }
}

2 个答案:

答案 0 :(得分:4)

它'悬挂'的原因是因为进程在同一个线程中运行。 使用BackgroundWorker将进度条进程移动到另一个线程。

要防止复制+粘贴,请参阅以下链接:

答案 1 :(得分:2)

防止这种情况的唯一方法是将工作负载委托给另一个线程。

您可以使用几个类来执行此操作:

后台工作者可能是最简单的方法,因为它提供了将结果返回给UI线程的方法。使用其他选项,您需要结果发送到正确的线程。

相关问题