C# Async, Await and using statements

Async, Await 是基于 .NEt 4.5架构的, 用于处理异步,防止死锁的方法的开始和结束, 提高程序的响应能力。比如:

Application area           Supporting APIs that contain async methods

 Web access                    HttpClient , SyndicationClient

 Working with files           StorageFileStreamWriterStreamReaderXmlReader

 Working with images       MediaCaptureBitmapEncoderBitmapDecoder

 WCF programming          Synchronous and Asynchronous Operations

 

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:

        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.

Then delete the pic in path, wihch is working properly after I use the using statement...

Without using the using statement, it shows IO exception said: 

Process Cannot Access the file “\Path” because it is being used by some other process

 

转载于:https://www.cnblogs.com/bruceyo/p/4026522.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值