Why should I use asynchronous operation over synchronous operation?
Asked Answered
R

6

5

I have always pondered about this.

Let's say we have a simple asynchronous web request using the HttpWebRequest class

class webtest1
{
    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("www.google.com");

    public webtest1()
    {
        this.StartWebRequest();
    }

    void StartWebRequest()
    {
        webRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), null);
    }

    void FinishWebRequest(IAsyncResult result)
    {
        webRequest.EndGetResponse(result);
    }
}

The same can be achieved easily with a synchronous operation:

class webtest1
{
    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("www.google.com");

    public webtest1()
    {
        webRequest.GetResponse();
    }
}

So why would I want to use the more convoluted async operation when a much simpler sync operation would suffice? To save system resources?

Reliquary answered 13/12, 2011 at 22:48 Comment(4)
Because you like a challenge?Lighthouse
You don't mention which platform you use but I can deduce it's not SilverLight. In SL you don't get to choose.Lighthouse
The funny thing is, that if I remember correctly, the async webrequest methods aren't completely async but block for parts of the operation, such as DNS lookup.Strunk
@Henk Just in general. Mine's only an example. Just happens to be web request related.Reliquary
F
6

A synchronous operation will prevent you from doing anything else while waiting for the request to complete or time out. Using an asynchronous operation would let you animate something for the user to show the program is busy, or even let them carry on working with other areas of functionality.

Fenestra answered 13/12, 2011 at 22:51 Comment(0)
C
9

If you make an asynchronous request you can do other things while you wait for the response to your request. If you make a synchronous request, you have to wait until you recieve your response until you can do something else.

For simple programs and scripts it may not matter so much, in fact in many of those situations the easier to code and understand synchronous method would be a better design choice.

However, for non-trivial programs, such as a desktop application, a synchronous request which locks up the entire application until the request is finished causes an unacceptable user expierence.

Corsetti answered 13/12, 2011 at 22:57 Comment(0)
F
6

A synchronous operation will prevent you from doing anything else while waiting for the request to complete or time out. Using an asynchronous operation would let you animate something for the user to show the program is busy, or even let them carry on working with other areas of functionality.

Fenestra answered 13/12, 2011 at 22:51 Comment(0)
C
6

The synchronous version is simpler to code but it masks a very serious problem. Network communication, or really an I/O operation, can block and for extended periods of time. Many network connections for example have a timeout of 2 minutes.

Doing a network operation synchronously means your application and UI will block for the entire duration of that operation. A not uncommon network hiccup could cause your app to block for several minutes with no ability to cancel. This leads to very unhappy customers.

Commonality answered 13/12, 2011 at 22:52 Comment(0)
C
4

Asynchronous becomes especially useful when you have more things going on than you have cores - for example, you might have a number of active web requests, a number of file access operations, and few DB calls, and maybe some other network operations (WCF or redis maybe). If all of those are synchronous, you are creating a lot of threads, a lot of stacks, and suffering a lot of context switches. If you can use an asynchronous API you can usually exploit pool threads for the brief moments when each operation is doing something. This is great for high throughput server environments. Having multiple cores is great, but being efficient is better.

In C# 5 this becomes, via await, no more work than your second example.

Cchaddie answered 13/12, 2011 at 22:55 Comment(2)
Looking forward to that. Any news of when it will be released?Reliquary
@James you mean RTM? No clue.Cchaddie
G
2

I was reading this the other day and a similar question has been pondered before:

Performance difference between Synchronous HTTP Handler and Asynchronous HTTP Handler

Guttery answered 13/12, 2011 at 22:52 Comment(1)
The question there is too specificCns
H
1

1) You are stuck to a single-threaded environment such as silverlight. Here you have no choice but to use async calls or the entire user thread will lock up.

2) You have many calls that take a long time to process. Why block your entire thread when it can go on and do other things while waiting for the return? For example if I have five function calls that each take 5 seconds, I would like to start all of them right away and have them return as necessary.

3) Too much data to process in the output synchronously. If I have a program that writes 10 gigabytes of data to the console and I want to read the output, I have a chance asynchronously to process line by line. If I do this synchronously then I will run out of buffer space and lock up the program.

Hootchykootchy answered 13/12, 2011 at 22:52 Comment(1)
3 is more an issue of streaming va buffering, which is orthogonal to async; to counter the example, you could also have a streaming sync API (Stream.Read for example, or ReadLine), or a fully-buffered async APICchaddie

© 2022 - 2024 — McMap. All rights reserved.