using System; using System.Collections.Generic; using System.ComponentModel;
using System.Data; using System.Drawing; using System.Linq; using System.Text;
using System.Threading; using System.Threading.Tasks; using
System.Windows.Forms; namespace winformLearning { public partial class Task学习 :
Form { public Task学习() { InitializeComponent(); } private void
button1_Click(object sender, EventArgs e) { //创建一个任务 Task<int> task = new
Task<int>(() => { int sum = 0; Console.WriteLine("使用Task执行异步操作.");//------2 for
(int i = 0; i < 100; i++) { Thread.Sleep(100); sum += i; } return sum; });
//启动任务,并安排到当前任务队列线程中执行任务(System.Threading.Tasks.TaskScheduler) task.Start();
Console.WriteLine("主线程执行其他处理"); //----1 //任务完成时执行处理。 Task cwt =
task.ContinueWith(t => { //Thread.Sleep(5000);
Console.WriteLine("任务完成后的执行结果:{0}", t.Result.ToString());//------4 });
task.Wait(); Console.WriteLine("task执行结束");//-----3 cwt.Wait();
Console.WriteLine("task回调执行结束");//-------5 } public void TastMethod1(string
name) { Thread.Sleep(6000); Console.WriteLine("name:"+name); } public void
TastMethod2(string name) { Thread.Sleep(3000); Console.WriteLine("name:" +
name); } } }