异步
await不会阻塞主线程(UI不会假死,IIS回收空闲线程),会把后面的操作封装成callback
Result会阻塞线程
async/await(Task) //await后不会开启新的线程,只有async里用Task.Run或Task.Factory.Startnew开启新线程后,await时才会等待线程,不加await时异步执行, await只能等待Task
static void Main(string[] args) { Console.WriteLine("Main Thread Id: {0}\r\n", Thread.CurrentThread.ManagedThreadId); Test(); Console.ReadLine(); } static async Task Test() { Console.WriteLine("Before calling GetName, Thread Id: {0}\r\n", Thread.CurrentThread.ManagedThreadId); var name = GetName(); //我们这里没有用 await,所以下面的代码可以继续执行 // 但是如果上面是 await GetName(),下面的代码就不会立即执行,输出结果就不一样了。 Console.WriteLine("End calling GetName.\r\n"); Console.WriteLine("Get result from GetName: {0}", await name); } static async Task<string> GetName() { // 这里还是主线程 Console.WriteLine("Before calling Task.Run, current thread Id is: {0}", Thread.CurrentThread.ManagedThreadId); return await Task.Run(() => { Thread.Sleep(1000); Console.WriteLine("'GetName' Thread Id: {0}", Thread.CurrentThread.ManagedThreadId); return "Jesse"; }); }
HttpClient
client.GetAsync("http://google.com").Result
await client.GetAsync("http://google.com")
response.Content.ReadAsAsync().Result
await response.Content.ReadAsAsync()
Task<HttpResponseMessage> responseTask= httpClient.GetAsync(“http://en.wikipedia.org/”); //创建Task并执行
HttpResponseMessage response = await responseTask; //等待task执行完毕
//并发 public async Task Await3Task() { var task3 = Delay3000Async(); var task2 = Delay2000Async(); var task1 = Delay1000Async(); await task3; await task2; await task1; } //非并发 public async Task Await3DelayAsync() { await Delay3000Async(); await Delay2000Async(); await Delay1000Async(); } //并发,这里甚至可以把var task3等去掉,直接调用xxxAsync(),只是会出现警告的波浪罢了 public void NoAwait3Task() { var task3 = Delay3000Async(); var task2 = Delay2000Async(); var task1 = Delay1000Async(); }
线程间通信
winform invode
wpf dispacher
asp.net SynchronizationContext(将任务(delegate)以队列的方式放入context中,再把context关联到
具体线程上,多个线程可关联相同的SynchronizationContext,SynchronizationContext.Current获取
当前线程关联的上下文)
url:http://www.cnblogs.com/jesse2013/p/Asynchronous-Programming-In-DotNet.html
url:http://www.cnblogs.com/richieyang/p/5020849.html