asynchronous programming and multi -threading: key differences
asynchronous programming and multi -threads are often confused, but they are completely different concepts.
asynchronous programming
The core of asynchronous programming is non -blocking operation
. When encountering the "AWAIT" expression in the asynchronous method, it will not block the thread execution to wait for the task to complete. Instead, it will register the remaining part of the method into a continuation and pay the control of the control right to the caller of the asynchronous method.It is important that the asynchronous method does not need to create additional threads
. Because the asynchronous method is running in the current synchronization context, only thread time is used during activity. "TASK.RUN" can uninstall the CPU dense work to the background thread, but this is invalid for the process of just waiting for the result.Multi -thread
Multi -threads involve allocating tasks to multiple work threads. Each processor handles the assignment task independently. Coordinate these work threads to prevent resource conflicts and ensure that appropriate compensation increases complexity. A simple metaphor
The example of the restaurant can help understand the difference between the two:
Synchronous:
Fry the eggs first, then bake the bread.Single -threading:
Consider the example of Jon Skeet:
When calling , it will trigger asynchronous operation without blocking the call thread.
Register the remaining method as a continuation, and execute when the length of the website is available. When operating here, the caller can continue to perform other tasks.
After the completion, the execution continues, and the label text is set with the length of the website.
<code class="language-c#">async void DisplayWebsiteLength ( object sender, EventArgs e ) { label.Text = "Fetching ..."; using ( HttpClient client = new HttpClient() ) { Task<string> task = client.GetStringAsync("http://csharpindepth.com"); string text = await task; label.Text = text.Length.ToString(); } }</code>
The above is the detailed content of Asynchronous Programming vs. Multithreading: What's the Difference?. For more information, please follow other related articles on the PHP Chinese website!