c# - 主进程在启动另一个线程后被卡住

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

最佳答案

您的 StartThread() 方法包括一个 Thread.Sleep(5000) ...这发生在您的按钮单击方法中,因此使 UI 线程休眠。此外,看起来您在 UI 线程上有一个无限循环,因为 continue_ 永远不会设置为 false

我猜你想在这里实现什么,但这可能会有所帮助:

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

关于c# - 主进程在启动另一个线程后被卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35342035/

相关文章:

c# - 从存储过程中获取 XML

c# - RESTful (Web API) 服务中的非 CRUD 操作

c# - 如何使用 EPPlus 读取 excel

c# - 将格式 xxxxxxxxxx 更改为 xxx-xxx-xxxx

c# - DataGridView 行背景颜色没有改变

java - 创建新线程 - Android

java - 在图书馆管理系统上使用多线程

java - Java 执行器框架中对终止线程的控制

WinForms 选项卡控件替换可用于大量选项卡

c# - 表单在客户端桌面区域内移动