【问题标题】:Threading on WinformsWinforms 上的线程
【发布时间】:2019-09-19 15:19:33
【问题描述】:

我正在自学如何在复杂的循环中处理大量数字。 在主程序中,它会调用一个方法来执行一些动作。 在我正在处理的示例中,它只是以秒为单位显示时间。

在我工作时,表单会出现无响应并崩溃。 画面看起来像

当程序运行时,每一秒都会输出到屏幕上,让用户看到程序仍在运行并且没有响应。

代码如下

private void BtnStart_Click(object sender, EventArgs e)
{
    Stopwatch stopwatch = new Stopwatch();
    stopwatch.Start();

    label1.Text = "Start";
    label2.Text = "Started";

    dataGridView1.ColumnCount = 1;
    dataGridView1.Columns[0].Name = "Number";

    for (int index1 = 0; index1 < limit; index1++)
    {
        for (int index2 = 0; index2 < limit; index2++)
        {
            for (int index3 = 0; index3 < limit; index3++)
            {
                if ((stopwatch.ElapsedMilliseconds % 1000) == 0)
                {
                    timeCount++;
                    AddRowToDG();
                }
                count++;
            }
        }
    }

    label1.Text = "The count is " + count.ToString();
    // Stop.
    stopwatch.Stop();
    Double myTime = stopwatch.ElapsedMilliseconds;
    label2.Text = (myTime / 1000).ToString();
}

private void AddRowToDG()
{
    dataGridView1.Rows.Add(timeCount.ToString());
}

如果我使用 150 以上的限制,程序将无响应。 在我将实际使用的编程中,将是 10 的 12 次方。

根据我所做的研究,有可以使用的任务和线程。 我应该使用哪种方法,从哪里可以获得最好的资源来帮助我在未来做出选择?

【问题讨论】:

  • 那么您肯定需要阻止 UI 冻结的线程在哪里??
  • 您应该在与 UI 不同的线程\任务上操作非 UI 活动。您的表单正在冻结,因为在您的 BtnStart 代码运行时它没有被更新
  • “崩溃”信息在哪里?
  • 开始阅读Asynchronous programming

标签: c# multithreading task


【解决方案1】:

C# 语言有 System.Threading.Tasks.TaskSystem.Threading.Thread 类,但对于 Windows 窗体,您应该使用 System.ComponentModel.BackgroundWorker。有DoWork 事件可以在不同的线程中执行您的应用程序逻辑。

【讨论】:

  • 您可以在 WinForms 中使用 Task。没有问题。
猜你喜欢
  • 2015-06-05
  • 1970-01-01
  • 1970-01-01
  • 2012-12-04
  • 2011-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多