Quantcast
Channel: What is the difference between asynchronous programming and multithreading? - Stack Overflow
Viewing all articles
Browse latest Browse all 3

What is the difference between asynchronous programming and multithreading?

$
0
0

I thought that they were basically the same thing — writing programs that split tasks between processors (on machines that have 2+ processors). Then I'm reading this, which says:

Async methods are intended to be non-blocking operations. An awaitexpression in an async method doesn’t block the current thread whilethe awaited task is running. Instead, the expression signs up the restof the method as a continuation and returns control to the caller ofthe async method.

The async and await keywords don't cause additional threads to becreated. Async methods don't require multithreading because an asyncmethod doesn't run on its own thread. The method runs on the currentsynchronization context and uses time on the thread only when themethod is active. You can use Task.Run to move CPU-bound work to abackground thread, but a background thread doesn't help with a processthat's just waiting for results to become available.

and I'm wondering whether someone can translate that to English for me. It seems to draw a distinction between asynchronicity (is that a word?) and threading and imply that you can have a program that has asynchronous tasks but no multithreading.

Now I understand the idea of asynchronous tasks such as the example on pg. 467 of Jon Skeet's C# In Depth, Third Edition

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();    }}

The async keyword means "This function, whenever it is called, will not be called in a context in which its completion is required for everything after its call to be called."

In other words, writing it in the middle of some task

int x = 5; DisplayWebsiteLength();double y = Math.Pow((double)x,2000.0);

, since DisplayWebsiteLength() has nothing to do with x or y, will cause DisplayWebsiteLength() to be executed "in the background", like

                processor 1                |      processor 2-------------------------------------------------------------------int x = 5;                                 |  DisplayWebsiteLength()double y = Math.Pow((double)x,2000.0);     |

Obviously that's a stupid example, but am I correct or am I totally confused or what?

(Also, I'm confused about why sender and e aren't ever used in the body of the above function.)


Viewing all articles
Browse latest Browse all 3

Latest Images

Trending Articles





Latest Images