c# - 使用 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();
}
}
}
解决方案
使用任务而不是线程。
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();
}
推荐阅读
- nginx - 在 Ubuntu 上运行 ASP .NET Core 网站时的 Nginx 配置问题
- javascript - javascript中删除的时间复杂度是多少
- google-apps-script - Apps 脚本:如何在工作表 api 进行更改后捕获单元格的 oldValue?
- r - 从 ui 和 server 以外的其他文件调用输入
- python - python NewRandomAccessFile 无法创建/打开 tfhub_module.pb tensorflow
- java - 我想要接受 https 请求并将此请求发送到 http 上的其他应用程序并将此 http 响应发送回 https req 的 Spring Boot 应用程序
- laravel - Laravel 查找存在于 CarbonPeriod 中的记录
- fedora - Fedora CoreOS 使用 Zincati/FleetLock 自动升级
- reactjs - 预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段 access-control-allow-credentials
- windows - 在 Windows 上使用 Git 的 GPG 代理上的 IPC 错误