async,await,Task 的一些用法
async,await,Task 的一些用法
private void Form1_Load(object sender, EventArgs e) { Display(); } public async void Display() { int result = await GetValueAsync(123); this.label1.Text = "Value is : " + result; } public Task<int> GetValueAsync(int num) { // 方法1 return Task.Run(() => { return DoSomething(num); }); // 方法2 return Task.Run(() => { //DoSomething System.Threading.Thread.Sleep(3000); return num; }); // 方法3 object state = num; Task<int> task = new Task<int>(DoSomething, state); task.Start(); return task; } public int DoSomething(int num) { System.Threading.Thread.Sleep(3000); return num; } public int DoSomething(object state) { System.Threading.Thread.Sleep(3000); return Convert.ToInt32(state); }