首页 > 解决方案 > 使用 Thread.Join() 时表单冻结,如何防止?

问题描述

我想显示 2 个线程完成的时间间隔。我的表单上有 2 个文本框、1 个标签和一个按钮。我正在使用以下代码,但是当我使用线程 Join() 方法时,表单会冻结。我该如何解决?

using System;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;

namespace ThreadingApp {
    public partial class Form1 : Form
    {
        public void func1()
        {
            for ( long i=0; i <= 2000; i++)
            {
                this.Invoke(new Action(() =>
                {
                    textBox1.Text = i.ToString();
                }));
                Thread.Sleep(1);
            }
        }

        public void func2()
        {
            for (long i = 0; i <= 200; i++)
            {
                this.Invoke(new Action(() =>
                {
                    textBox2.Text = i.ToString();
                }));
                Thread.Sleep(20);
            }
        }
    
        public Form1()
        {
            InitializeComponent();
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            Stopwatch s = new Stopwatch();
            Thread th1 = new Thread(func1);
            Thread th2 = new Thread(func2);
            s.Start();
            th1.Start();
            th2.Start();
            th1.Join(); th2.Join();
    
            s.Stop();
            lblTime.Text = s.ElapsedMilliseconds.ToString();
        }    
    }
}

标签: c#multithreadingwinforms

解决方案


使用任务而不是线程。

private async void Button1_Click(object sender, EventArgs e)
{
    Stopwatch s = new Stopwatch();
    s.Start();

    var task1 = Task.Run(func1);
    var task2 = Task.Run(func2);

    await Task.WhenAll(task1, task2);

    s.Stop();
    lblTime.Text = s.ElapsedMilliseconds.ToString();
}

推荐阅读