当我使用Thread.Join()时表格冻结

时间:2020-08-12 18:23:58

标签: c# multithreading winforms

我想显示两个线程完成的时间间隔。我的表单上有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();
        }    
    }
}

1 个答案:

答案 0 :(得分:1)

使用任务代替线程。

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();
}
相关问题