方法一
private void button1_Click(object sender, EventArgs e)
{
DateTime start = DateTime.Now;
List<Task> taskList = new List<Task>();
taskList.Add(Task.Run(() =>
{
Thread.Sleep(3000);
Console.WriteLine("三秒输出");
}));
taskList.Add(Task.Run(() =>
{
Thread.Sleep(7000);
Console.WriteLine("七秒输出");
}));
taskList.Add(Task.Run(() =>
{
Thread.Sleep(5000);
Console.WriteLine("五秒输出");
}));
//等待结束
Task.WaitAll(taskList.ToArray());
DateTime end = DateTime.Now;
int num = GetTimeSpanSeconds(start, end);
Console.WriteLine($"三个线程已执行完毕,用时:{num}s");
}
/// <summary>
/// 两个时间间隔秒数
/// </summary>
/// <param name="startTime"></param>
/// <param name="endTime"></param>
/// <returns></returns>
public static int GetTimeSpanSeconds(DateTime startTime, DateTime endTime)
{
TimeSpan ts = endTime.Subtract(startTime);
int sec = (int)ts.TotalSeconds;
return sec;
}
方法二
private void button1_Click(object sender, EventArgs e)
{
DateTime start = DateTime.Now;
AutoResetEvent[] watchers = new AutoResetEvent[3];
watchers[0] = new AutoResetEvent(false);
//启动10个线程输出10个数字
new Thread(() =>
{
Thread.Sleep(3000);
Console.WriteLine("三秒输出");
watchers[0].Set(); //线程执行完的时候通知
}).Start();
watchers[1] = new AutoResetEvent(false);
//启动10个线程输出10个数字
new Thread(() =>
{
Thread.Sleep(7000);
Console.WriteLine("七秒输出");
watchers[1].Set(); //线程执行完的时候通知
}).Start();
watchers[2] = new AutoResetEvent(false);
//启动10个线程输出10个数字
new Thread(() =>
{
Thread.Sleep(5000);
Console.WriteLine("五秒输出");
watchers[2].Set(); //线程执行完的时候通知
}).Start();
WaitHandle.WaitAll(watchers); //确保所有线程都执行完毕
DateTime end = DateTime.Now;
int num = GetTimeSpanSeconds(start, end);
Console.WriteLine($"三个线程已执行完毕,用时:{num}s");
}
/// <summary>
/// 两个时间间隔秒数
/// </summary>
/// <param name="startTime"></param>
/// <param name="endTime"></param>
/// <returns></returns>
public static int GetTimeSpanSeconds(DateTime startTime, DateTime endTime)
{
TimeSpan ts = endTime.Subtract(startTime);
int sec = (int)ts.TotalSeconds;
return sec;
}
Copyright © 广州京杭网络科技有限公司 2005-2024 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有