After two days of intensive study , Read a lot of webpages , Click on a lot of key points blogs, Finally, I have a basic understanding of async/await How to use it together , To sum up

1. async/await It should be just a grammatical dessert , Let programmers who want to run programs asynchronously focus on code logic , And don't let the original Begin... End... Type or IAsync ...Async The old asynchronous belt is getting farther and farther away . Think of just trying to write Tcp Listener When , It's a nightmare . The asynchronous response must be placed in another callback method or event , The asynchronous reception from the asynchronous response must be put into another callback method or event again , It's even scarier , How to cycle them .

2. async/await Method of identification ,“ It doesn't create extra threads on its own initiative ”—— This sentence is easy to misunderstand .《Async and Await The principle of asynchronous programming 》 This article is quite detailed , asynchronous , Must be multithreaded , Not to mention from UI Thread started . It's just that multithreading is Framework The transparency is off , Users don't have to think about how to create threads themselves , How to recycle , How to catch anomalies , You have to make the code look better .

3. await I fell into a misunderstanding at the beginning , Think of using var result = await FunRun(...) This kind of writing ,FunRun() Methods will run asynchronously without blocking UI Threads , This is wrong , I've overlooked a very serious problem . Let's take a look at the original error code :

 private async Task<TimeSpan> Download(Uri address, string fileName)
this.uri = address;
this.fileName = fileName;
DateTime start = DateTime.Now;
HttpWebRequest request;
HttpWebResponse response = null;
request = (HttpWebRequest)WebRequest.Create(address);
response = (HttpWebResponse)request.GetResponse();
using (Stream httpStream = response.GetResponseStream())
using (FileStream writer = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read))
byte[] buffer = new byte[];
int readLength = httpStream.Read(buffer, , buffer.Length);
while (readLength > )
writer.Write(buffer, , readLength);
readLength = httpStream.Read(buffer, , buffer.Length);
if (response != null) { response.Close(); }
} return DateTime.Now - start;

The code completes the function of downloading a resource to a specified location , There is no mistake in logic itself , It seems to be a standard with async Labelling and Task<T> Method of return type , So I used it slowly .

 private async void button1_Click(object sender, EventArgs e)
// Something that skips part of the logical judgment
...... TestApp.HttpDownloader.HttpDownloaderEngine hdEngine = new HttpDownloaderEngine();
var time = await hdEngine.Download(address, saveFileTextBox.Text);
MessageBox.Show(string.Format(" Download complete , Total time consuming {0} second ", time.Seconds.ToString()));

Call the wrong way to write

Button1 Of Click There is no problem with the incident itself , I also carefully added async Mark ( Of course , I'm not allowed to go there ), Everything's fine. I'll run it right away , It turns out to be confusing , It did download successfully Mp3 To my computer , No matter how long it takes , my UI It's still synchronized , Cannot respond until execution is complete . Where is the problem ?

People need to rest , Study -> rest -> Digestion , After combing and reviewing the data again , I found out the second 3 What I said at the beginning ,Bug lie in HttpDownloadEngine Of Download The method I marked async,button_click mistook Download Method can do asynchronous work ,button_click That's right , Wrong Download The method is not , There is no “ Code executed asynchronously ”! in other words ,Download There is no one in the method await , This makes it possible to mark async Of Download Methods are still synchronized ,button_click A synchronization method is called and executed synchronously .

How to modify , stay Download The key point in the method is execution await Task<T> ....Async , Such as  readLength = await responseStream.ReadAsync(buffer, 0, buffer.Length);, The key point is where asynchronous execution is really needed .

4. I want to thank you Microsoft, I'm not a God , I'm a fan , It was Microsoft that drew on and created .Net And unparalleled VS, Let me and people like me appreciate more of the charm of the computer , The charm , From creating and sharing to others .

Post a picture of the result of the download

Asycn/Await More articles on asynchronous programming

  1. Asycn/Await Asynchronous programming ( Two )

    After a long time 4 Days of learning and practice , Done WinForm Next .Net 4.5 The basic asynchronous application of , Implemented a Http Protocol download test program , For later use .Net 4.5 Accumulate knowledge and experience . This small program completes the following tasks ...

  2. Asycn/Await Asynchronous programming

    Asycn/Await Asynchronous programming ( Two )   After a long time 4 Days of learning and practice , Done WinForm Next .Net 4.5 The basic asynchronous application of , Implemented a Http Protocol download test program , For later use .Net ...

  3. Async and Await The principle of asynchronous programming

    1. brief introduction from 4.0 Version start .NET Introducing parallel programming library , Users can quickly develop parallel computing and parallel task processing programs through this library . stay 4.5 In the version .NET And the introduction of Async and Await Two new keywords , Parallel programming at the language level ...

  4. async And await The foundation of asynchronous programming

    original text :async And await The foundation of asynchronous programming I haven't written a blog for a long time , Time interval 5 Months , Here is a well prepared article , I hope you can get something , Yes async and await There is a deeper understanding of . async and a ...

  5. 【 turn 】C# Async/Await Best practices in asynchronous programming

    Async/Await Best practices in asynchronous programming Stephen Cleary recently , There's a lot about Microsoft .NET Framework 4.5 Added right to async and await the ...

  6. Li Hongqiang iOS The function of development The beginning of programming

    Functional expression The beginning of programming   Studying recently Erlang and Python.Erlang It's a completely functional programming language ,Python Language is an object-oriented language , But its syntax introduces a lot of functional programming ideas . The more we study, the more we feel that the functional programming idea can ...

  7. .NET Web Why should we use async/await Asynchronous programming

    Preface What is? async/await? await and async yes .NET Framework4.5 frame .C#5.0 Technology in grammar , The goal is to simplify the asynchronous programming model . async and await The relationship between ? asy ...

  8. C# in Thread,Task,Async/Await Asynchronous programming

    What is asynchronous Synchronous and asynchronous are mainly used to modify methods . When a method is called , The caller needs to wait for the method to finish executing and return to continue , We call this method synchronous : When a method is called, it immediately returns , And get a thread to execute the internal business of the method , transfer ...

  9. async/await Asynchronous programming ( Reprint )

    Reprinted address : Preface Studying recently Web Api I came into contact with async/await, This property is .NET 4.5 introduce ...

Random recommendation

  1. Java Basics - Rewriting methods

    Generally we need to override... On new classes , Implementation of two classes : class Animal{ public void move(){ System.out.println(" Animals can move "); } } c ...

  2. eclipse Initiate error reporting \workspace\.metadata\.log

    eclipse Initiate error reporting , Let's see .metadata\.log journal eclipse It won't start , Let's see .metadata\.log journal , The above is the error prompt in the log . terms of settlement : Delete .metadata\.plug ...

  3. .net Application YUI dependent dll Compress js ( According to your own rules , I think it's powerful and interesting )

    Write it at the front Whether it's front-end or back-end , Whether it's understanding javaScript I still don't understand JavaScript People who , I want to know more or more js The effect of compression on page performance . I used to use online compression tools to compress js, ...

  4. DB2 Date subtraction

    Simple method : Use days Date of character type :2012-01-01,2012-01-11 values  days(date('2012-01-11')) - days(date('2012-01-01' ...

  5. xhtml+css Basic knowledge of 1

    style Header styles : In the label <div style="width:400px; height:200px; background:red;"> block </div> Inside ...

  6. margin overlap

    margin Overlap is what we often say CSS Outer margin merge ,W3C The following definitions are given : The outer margin combination refers to , When two vertical margins meet , They will form an outer margin . The height of the combined outer margin is equal to the greater of the height of the two merged outer margins ...

  7. Android Abnormal analysis ( turn )

    About anomalies abnormal ? An exception is an unexpected problem in a program , Since it was unexpected , It may not be within the scope of the original logic , Out of code control , Software may appear all kinds of strange phenomena . such as :android The common abnormal phenomena of the system are whether the application responds . ...

  8. WebApi series ~ I won't support it put and delete Requested resolution

    Back to directory reason Due to the installation of webDAV Module induced , stay web.config Inside system.webserver node , take webdav Module movement take http The requested permission is open Realization <system.webS ...

  9. Jenkins Change to Chinese language display

    To system management     Download the following plug-in interface in plug-in management  Localization: Chinese (Simplified) Search with ctrl+f To search , Do not use Jenkins Below filter Only ...

  10. mosquitto Simple application

    1. sketch A message push protocol MQTT v3.1 Open source message broker for , Offer lightweight , Support for releasable / Subscribable message push mode , Make short message communication between devices simple , For example, low-power sensors are widely used now , mobile phone ...