主进程在启动另一个线程后被冻结

时间:2016-02-11 14:29:17

标签: c# multithreading winforms

我正在尝试编写一个在两个系统之间传输数据的应用程序。此应用程序由用户使用,因此它是WinForm应用程序。当通过单击用户启动数据传输时,即使我在另一个线程中启动数据传输,GUI也会被冻结。我做错了什么但我无法弄清楚。这是我的简化代码....

我做错了什么?

// Button Click Event
private void btnStart_Click(object sender, EventArgs e)
{
   StartThread();
}

// This starts the threaad.
public static void StartThread()
{
   string msg = string.Empty;
   int i = 0;

   continue_ = true;

   if (list != null)
   {
       while (continue_)
       {
           i++;
           Thread.Sleep(5000);

           Thread thrd1 = new System.Threading.Thread(() => Test());
           thrd1.Start();
       }
   }
}

// This is a simplified code.
public static void Test() 
{
        string msg = string.Empty;
        int i = 0;
        continue_ = true;
        while (continue_)
        {
            i++;
            Thread.Sleep(5000);
            FormMain.dal.ExecuteQuery("INSERT INTO A_TEST VALUES('"+i+"')",null,CommandType.Text,out msg);
        }
}

3 个答案:

答案 0 :(得分:2)

你的StartThread()方法包含一个Thread.Sleep(5000)......这是在你的按钮点击方法中发生的,因此使得UI线程处于睡眠状态。此外,看起来您在UI线程上有一个无限循环,因为continue_永远不会设置为false

我猜你在这里想要达到的目标,但这可能有所帮助:

public static void StartThread()
{
   Thread thrd1 = new System.Threading.Thread(() => Test());
   thrd1.Start();
}

答案 1 :(得分:0)

让我们看一下StartThread中的这个块:

while (continue_)
{
    i++;
    Thread.Sleep(5000);

    Thread thrd1 = new System.Threading.Thread(() => Test());
    thrd1.Start();
}
  1. 您在continue_上有依赖循环,但您永远不会将其更改为false。所以你首先得到一个无限循环,这会导致GUI冻结。
  2. 为什么要修改i,但从不使用它,所以只需删除它即可。
  3. 您也不需要Thread.Sleep(5000);。但是,如果您真的想等一段时间,可以使用an async delay。它将使GUI免费,以便GUI工作直到延迟完成。但为此,您必须将StartThread声明为async

答案 2 :(得分:-1)

在你的:

Thread.Sleep(5000);

您使用returnValue

然而,这仍然针对您的主线程。 我建议你删除这一行。

另外,为什么你从不使用变量'i'?

相关问题