private void button1_Click(object sender, EventArgs e)
{
//thread.sleep 阻碍当前线程
Thread.Sleep(3000);
MessageBox.Show("素菜做好了");
Thread.Sleep(5000);
MessageBox.Show("荤菜做好了");
}
private void button2_Click(object sender, EventArgs e)
{
//多线程
Thread t = new Thread(() =>
{
Thread.Sleep(3000);
MessageBox.Show("素菜做好了");
Thread.Sleep(5000);
MessageBox.Show("荤菜做好了");
});
t.Start();
}
private void button3_Click(object sender, EventArgs e)
{
//推荐使用task
Task.Run(() =>
{
Thread.Sleep(3000);
MessageBox.Show("素菜做好了");
Thread.Sleep(5000);
MessageBox.Show("荤菜做好了");
});
}
private void button4_Click(object sender, EventArgs e)
{
//同时并行运行的,利用cpu 多核的原理
Task.Run(() =>
{
Thread.Sleep(3000);
MessageBox.Show("素菜做好了");
});
Task.Run(() =>
{
Thread.Sleep(5000);
MessageBox.Show("荤菜做好了");
});
}
private async void button5_Click(object sender, EventArgs e)
{
//等待菜做好了,才打印菜做好了,大家快来吃饭。
await Task.Run(() =>
{
Thread.Sleep(3000);
MessageBox.Show("素菜做好了");
Thread.Sleep(5000);
MessageBox.Show("荤菜做好了");
});
MessageBox.Show("菜做好了,大家快来吃饭。");
}
private async void button6_Click(object sender, EventArgs e)
{
//当素材做好了,才开始做荤菜,这不是并行的了。
await Task.Run(() =>
{
Thread.Sleep(3000);
MessageBox.Show("素菜做好了");
});
await Task.Run(() =>
{
Thread.Sleep(5000);
MessageBox.Show("荤菜做好了");
});
MessageBox.Show("菜做好了,大家快来吃饭。");
}
private void button7_Click(object sender, EventArgs e)
{
List<Task> ts = new List<Task>();
//这样做又是并行的了。
ts.Add(Task.Run(() =>
{
Thread.Sleep(3000);
MessageBox.Show("素菜做好了");
}));
ts.Add(Task.Run(() =>
{
Thread.Sleep(5000);
MessageBox.Show("荤菜做好了");
}));
Task.WhenAll(ts).ContinueWith(t =>
{
MessageBox.Show("菜做好了,大家快来吃饭。");
});
}