Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use asynchronous operation over synchronous operation?

Tags:

c#

concept

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?

like image 715
deutschZuid Avatar asked Dec 13 '11 22:12

deutschZuid


2 Answers

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.

like image 163
Tom Neyland Avatar answered Sep 30 '22 18:09

Tom Neyland


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.

like image 34
Matt Lacey Avatar answered Sep 30 '22 19:09

Matt Lacey