C# 多线程示例:使用 Thread 类实现多个线程同时运行
namespace Threaddemo { public partial class MainForm : Form { private Thread thread1, thread2, thread3; private DateTime startTime;
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
// 初始化线程
thread1 = new Thread(new ThreadStart(Worker1));
thread2 = new Thread(new ThreadStart(Worker2));
thread3 = new Thread(new ThreadStart(Worker3));
}
private void button1_Click(object sender, EventArgs e)
{
// 开始运行三个线程
startTime = DateTime.Now;
thread1.Start();
thread2.Start();
thread3.Start();
}
private void Worker1()
{
// 线程1的工作
while (DateTime.Now.Subtract(startTime).TotalSeconds < 60)
{
UpdateLabel(label1, DateTime.Now.Subtract(startTime).ToString('hh\:mm\:ss'));
}
}
private void Worker2()
{
// 线程2的工作
while (DateTime.Now.Subtract(startTime).TotalSeconds < 60)
{
UpdateLabel(label2, DateTime.Now.Subtract(startTime).ToString('hh\:mm\:ss'));
}
}
private void Worker3()
{
// 线程3的工作
while (DateTime.Now.Subtract(startTime).TotalSeconds < 60)
{
UpdateLabel(label3, DateTime.Now.Subtract(startTime).ToString('hh\:mm\:ss'));
}
}
private void UpdateLabel(Label label, string text)
{
// 更新 Label 的文本
if (label.InvokeRequired)
{
label.Invoke(new Action<Label, string>(UpdateLabel), label, text);
}
else
{
label.Text = text;
}
}
}
}
namespace Threaddemo
{
internal static class Program
{
///
namespace Threaddemo
{
internal static class Program
{
///
原文地址: https://www.cveoy.top/t/topic/mF7J 著作权归作者所有。请勿转载和采集!