Async, Await 是基於 .NEt 4.5架構的, 用於處理異步,防止死鎖的方法的開始和結束, 提升程序的響應能力。好比:多線程
Application area Supporting APIs that contain async methods架構
Web access HttpClient , SyndicationClient異步
Working with files StorageFile, StreamWriter, StreamReader, XmlReaderasync
Working with images MediaCapture, BitmapEncoder, BitmapDecoderspa
WCF programming Synchronous and Asynchronous Operations.net
Async, Await 不會產生新的線程。 可是Task.Run 方法就是多線程的。 Asynchronous code is code that returns upon completion. By Task.Run, we can make is a multithreaded.線程
Take files as an example I encountered today:code
public async Task SendFallMail(string path){ try { mail.Subject = subjectFall; mail.Body = "Fall down!"; using (MailMessage ms = mail) { ms.Attachments.Add(new Attachment(path)); using (SmtpClient sc = SmtpServer) { Task t = Task.Factory.StartNew(() => { sc.Send(ms); }); await t; } } File.Delete(path); } catch (Exception ex) { MessageBox.Show(ex.ToString()); }
It should wait t which is sending an e-mail wihich attached an picture in path.xml
Then delete the pic in path, wihch is working properly after I use the using statement...blog
Without using the using statement, it shows IO exception said: