Comprehensive parsing of asynchronous programming in C #

Source: Internet
Author: User
Tags foreach call back

When we handle some long line calls, often causes the interface to stop responding or the IIS thread takes up too many issues, this time we need more asynchronous programming to fix these problems, but usually it is easier said than done, it is true that asynchronous programming is a completely different programming idea than synchronous programming. , for the developers accustomed to synchronous programming, in the development process is more difficult, controllability is not strong is its characteristics.

In. NET Framework5.0 species, Microsoft has a new language feature for us, let's use asynchronous programming as close and simple as using synchronous programming, and this article will explain some of the limitations of the previous version of the framework based on the callback ethics asynchronous programming model and the new API if we can simply do the same development task.

Why to asynchronous

All along, the use of remote resources programming is a confusing problem, different from "local resources", remote resources access will always have a lot of unexpected situations, network environment unstable machine server failure, will cause a lot of programmers completely uncontrollable problems, So this requires that programmers need more to protect remote resource calls, management calls cancellation, supermarkets, thread waiting, and processing threads for a long time did not respond to the situation. And in. NET, we often ignore these challenges, in fact we will have a variety of unused patterns to deal with asynchronous programming, such as in the processing of IO-intensive operations or high latency operations without testing the thread, most of the cases we have synchronous and asynchronous two methods to do this thing. The problem is that the current patterns are very easy to cause confusion and code errors, or developers will give up and then use blocking to develop.

And in today's. NET, it provides a programming experience that is very close to synchronous programming, and does not require a developer to deal with many of the situations that only occur in asynchronous programming, and the asynchronous invocation will be clear and opaque, combined with easy and synchronized code.

A bad experience in the past

The best way to understand this problem is our most common scenario: the user interface has only one thread all of the work is running on this thread, and the client program cannot react to the user's mouse time, most likely because the application is being blocked by a time-consuming operation, This may be because the thread is waiting for a network ID or is doing a CPU-intensive calculation, when the user interface does not get run time and the program is in a busy state, which is a very poor user experience.

For many years, the solution to this problem is to do the invocation of the asynchronous flower, not wait for the response, return the request as soon as possible, so that other events can be executed at the same time, only when the request has the final feedback to the application so that the client code can execute the specified code.

The problem is that the asynchronous code completely destroys the code flow, and the callback agent explains how it works later, but how to wait in a while loop? An If statement? a try block or a using block? How do you explain "what to do next"?

Look at one of the following examples:

public int sumpagesizes (IList URIs)

{

int total = 0;

foreach (Var uri in URIs)

{

Txtstatus.text = string. Format ("Found {0} bytes ...", total);

var data = new WebClient (). Downloaddata (URI);

Total + + data. Length;

}

Txtstatus.text = string. Format ("Found {0} bytes Total", total);

return total;

}

This method downloads files from a URI list, statistics their size and update state information at the same time, obviously this method does not belong to the UI thread because it takes a long time to complete, so it will completely suspend the UI, but we also want the UI to be continuously updated, how to do?

We can create a background program that continues to send data to the UI thread to get the UI to update itself, which seems wasteful because the thread spends most of the time waiting and downloading, but sometimes that's exactly what we need to do. In this example, WebClient provides an asynchronous version of the Downloaddata method-downloaddataasync, which returns immediately and then triggers an event after downloaddatacompleted, This allows the user to write an asynchronous version of the method to split what is to be done, call back immediately and complete the call on the next UI thread, thus no longer blocking the UI thread. Here is the first attempt:

public void Sumpagesizesasync (IList URIs)

{

Sumpagesizesasynchelper (URIs. GetEnumerator (), 0);

}

public void Sumpagesizesasynchelper (IEnumerator enumerator, int total)

{

if (enumerator. MoveNext ())

{

Txtstatus.text = string. Format ("Found {0} bytes ...", total);

var client = new WebClient ();

Client. downloaddatacompleted + = (sender,e) =>{

Sumpagesizesasynchelper (Enumerator, total + e.result.length);

};

Client. DownloadDataAsync (Enumerator. Current);

}

Else

{

Txtstatus.text = string. Format ("Found {0} bytes Total", total);

}

}

And then it was still bad, we broke a neat foreach loop and got a enumerator manually, each of which created an event callback. The code replaces the loop with recursion, which you should not be able to look straight at. Don't worry, it's not finished yet.

The original code returns a total and displays it, and the new one is returned to the caller before the statistics have been completed. How can we get a result to return to the caller, the answer is: The caller must support a fallback, we can call it after the statistics are complete.

But what about the exception? The original code does not pay attention to the exception, it will always pass to the caller, in the asynchronous version, we must extend back to allow the exception to propagate, when the exception occurs, we have to explicitly let it propagate.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.