【发布时间】: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代码运行时它没有被更新 -
“崩溃”信息在哪里?
标签: c# multithreading task