简体   繁体   English

新线程启动时C#表单挂起

[英]c# form hangs when new thread starts

I created new thread and start it ! 我创建了新线程并启动它!
When new thread is running, Winform is hanging(freezing) 当新线程正在运行时,Winform正在挂起(冻结)
Why winform hangs ? 为什么Winform挂起?
I want WinForm to move freely when I start a new thread 我希望WinForm在启动新线程时自由移动
how to do it ? 怎么做 ?
(I will not use thread pool here.) (我不会在这里使用线程池。)

        private void button4_Click(object sender, EventArgs e)
        {
            Thread t1 = new Thread(new ThreadStart(delegate ()
            {
                Run();
            }));
            t1.Start();
            t1.Join();
            MessageBox.Show("Complete");
        }

        private void Run()
        {
            int a = 1;
            for (int i = 1; i <= 999999999; i++)
            {
                ++a;
            }
        }

Read the documentation about Join . 阅读有关Join的文档

Blocks the calling thread until the thread represented by this instance terminates. 阻塞调用线程,直到该实例表示的线程终止。

So, you start the thread, and then you Join, which means, that your UI thread will block and wait for the thread to finish. 因此,您先启动线程,然后再加入,这意味着UI线程将阻塞并等待线程完成。

You could do async/await : 你可以做async / await

private async void button4_Click(object sender, EventArgs e)
{
    await Task.Run(Run);
    MessageBox.Show("Complete");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM