如何解决当我使用Thread.Join时表格冻结
我想显示两个线程完成的时间间隔。我的表单上有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();
}
}
}
解决方法
使用任务代替线程。
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();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。