C # Programming Summary (VI) Asynchronous programming

Source: Internet
Author: User

C # Programming Summary (VI) Asynchronous Programming 1, what is async?

Asynchronous operations are typically used to perform tasks that may take a long time to complete, such as opening large files, connecting to a remote computer, or querying a database. An asynchronous operation executes in a thread other than the main application thread. When an application invokes a method to perform an operation asynchronously, the application can continue execution while the Async method executes its task.

2. The difference between synchronous and asynchronous

Synchronization (synchronous): When an operation is performed, the application must wait for the operation to complete before it can continue execution.

Asynchronous (asynchronous): When an operation is performed, the application can continue execution while the asynchronous operation executes. In essence: An asynchronous operation that initiates a new thread, the main thread executes in parallel with the method thread.

3. The difference between async and multithreading

We already know that the essence of asynchrony is the opening of new threads. What is the difference between it and multithreading?

To put it simply: Asynchronous threads are managed by the thread pool, and multi-threading, we can control ourselves, and of course we can use thread pooling in multiple threads.

In the case of web-scraping, if you use asynchronous mode to implement it, it is managed using a thread pool. When an asynchronous operation is executed, the operation is dropped to a worker thread in the thread pool to complete. Asynchronously returns the worker thread to the thread pool when the I/O operation is started, which means that the work to get the Web page no longer consumes any CPU resources. Asynchronously notifies the thread pool by callback until the completion of the Web page is completed asynchronously. It can be seen that the asynchronous pattern, with the help of the thread pool, greatly saves CPU resources.

NOTE: DMA Direct memory access, as the name implies, the DMA function is to allow the device to bypass the processor, directly from memory to read the data. Data exchange through direct memory access can hardly deplete the CPU's resources. In the hardware, the hard disk, network card, sound card, video card and so on have the direct memory access function. The asynchronous programming model is what allows us to take full advantage of the hardware's direct memory access capability to free up CPU pressure.
application Scenarios for both:

Compute-intensive work, multi-threaded.
IO-intensive work, using asynchronous mechanisms.

4. Asynchronous Application

Many aspects of the. NET Framework support asynchronous programming capabilities, including:
1) file Io, stream io, socket IO.
2) network.
3) remoting channels (HTTP, TCP) and proxies.
4) XML Web Services created with ASP.
5) ASP. NET Web form.
6) Use the MessageQueue class for Message Queuing.

The. NET Framework provides two design patterns for asynchronous operations:
1) asynchronous operation using the IAsyncResult object.
2) An asynchronous operation that uses an event.
The IAsyncResult design pattern allows multiple programming models, but is more complex and difficult to learn, providing the flexibility that most applications do not require. If possible, class library designers should implement asynchronous methods using an event-driven model. In some cases, the Library designer should also implement a IAsyncResult-based model.

Asynchronous operations that use the IAsyncResult design pattern are implemented by two methods named begin operation name and end operation name, starting and ending the asynchronous operation operation name, respectively. For example, the FileStream class provides BeginRead and EndRead methods to read bytes asynchronously from a file. These two methods implement the asynchronous version of the Read method. After the begin operation name is called, the application can continue executing the instruction on the calling thread while the asynchronous operation executes on the other thread. Each time the begin operation name is called, the application should also call the end action name to get the result of the operation. The Begin Action name method begins an asynchronous operation operation name and returns an object that implements the IAsyncResult interface. The. NET Framework allows you to invoke any method asynchronously. Defines a delegate that has the same signature as the method you need to call; The common language runtime automatically defines the BeginInvoke and EndInvoke methods with the appropriate signatures for the delegate.

The IAsyncResult object stores information about asynchronous operations. The following table provides information about asynchronous operations.

Name

Description

AsyncState

Gets a user-defined object that qualifies or contains information about an asynchronous operation.

AsyncWaitHandle

Gets the WaitHandle that is used to wait for the asynchronous operation to complete.

completedsynchronously

Gets a value that indicates whether the asynchronous operation is complete synchronously.

IsCompleted

Gets a value that indicates whether the asynchronous operation is finished

5. Application examples

Case 1- Read File

Usually reading files is a relatively time-consuming task, especially when reading large files, common uploads and downloads. But we do not want to let users wait, users can also do other operations, can make the system has good interactivity. Here we write the synchronous and asynchronous calls to compare the instructions.

Read File class

Using system;using system.io;using System.threading;namespace asynsample{class FileReader {//<summary&        Gt        Cache pool//</summary> private byte[] buffer {get; set;}        <summary>///buffer size///</summary> public int buffersize {get; set;} Public FileReader (Int. buffersize) {this.            buffersize = buffersize; This.        Buffer = new Byte[buffersize]; }///<summary>///synchronous read///</summary>//<param name= "path" > File path </pa            ram> public void Synsreadfile (string path) {Console.WriteLine ("Synchronous read file Begin"); using (FileStream fs = new FileStream (path, FileMode.Open)) {fs.                Read (Buffer, 0, buffersize);                String output = System.Text.Encoding.UTF8.GetString (Buffer);            Console.WriteLine ("Read file information: {0}", output);       }                Console.WriteLine ("Synchronously read file End"); }///<summary>///Read files asynchronously///</summary>//<param name= "path" ></param&        Gt            public void Asynreadfile (string path) {Console.WriteLine ("Asynchronous read file Begin");            Executing the EndRead times error, FS has been freed, note that you cannot use the freed resource//using in async (FileStream fs = new FileStream (path, FileMode.Open))            {//Buffer = new Byte[buffersize]; Fs.            BeginRead (Buffer, 0, buffersize, Asyncreadcallback, FS);                } if (file.exists (path)) {FileStream fs = new FileStream (path, FileMode.Open); Fs.            BeginRead (Buffer, 0, buffersize, Asyncreadcallback, FS);            } else {Console.WriteLine ("The file does not exist"); }}///<summary>///</summary>//<param name= "AR" ></param > void asyncreadcalLback (IAsyncResult ar) {FileStream stream = ar.            AsyncState as FileStream;                if (stream! = null) {thread.sleep (1000); Reads the end stream.                EndRead (AR); Stream.                Close (); String output = System.Text.Encoding.UTF8.GetString (this.                Buffer);            Console.WriteLine ("Read file information: {0}", output); }        }    }}

Test Cases

Using system;using system.threading;namespace asynsample{    class program    {        static void Main (string[] args)        {            FileReader reader = new FileReader (1024x768);            Change to its own file path,            string path = "C:\\windows\\dai.log";            Console.WriteLine ("Start reading files ...");            Reader. Synsreadfile (path);            Reader. Asynreadfile (path);            Console.WriteLine ("I have a big beach here.");            DoSomething ();            Console.WriteLine ("Finally finished, enter any key, rest!") ");            Console.readkey ();                   }        <summary>/////         </summary>        static void DoSomething ()        {            Thread.Sleep ( );            for (int i = 0; i < 10000; i++)            {                if (i-888 = = 0)                {                    Console.WriteLine (Multiples of "888: {0}", i);                }            }        }    }}

Output Result:

Synchronous output:

Asynchronous output:

Results Analysis:

In the case of synchronous reads, the current thread reads the file while reading, and can only wait until the read is complete to perform the following actions

While asynchronous reading, is to create a new thread, read the file while the main thread continues execution. We can turn on Task Manager to monitor.

Case two--delegate-based asynchronous operation

The system comes with some classes with asynchronous invocation, how to make custom objects also have asynchronous function?

We can easily implement asynchrony with delegates.

Speaking of Begininvoke,endinvoke, we had to stop and look at the nature of the Commission. To facilitate understanding of the delegate, I define a simple delegate:

Public delegate string MyFunc (int num, DateTime DT);

Let's take a look at what this delegate looks like in a compiled assembly:

The delegate is compiled into a new type, with the three methods of Begininvoke,endinvoke,invoke. The combined use of the first two methods enables asynchronous invocation. The third method is called in a synchronous manner. Where the last two parameters of the BeginInvoke method are used for callbacks, the other parameters are matched to the input parameters of the delegate's wrapper method. The return value of the EndInvoke matches the return value of the delegate's wrapper method.

Asynchronous implementation File Download:

Using system;using system.text;namespace asynsample{//<summary>//Download commission///</summary>//&lt    ;p Aram Name= "FileName" ></param> public delegate string aysndownloaddelegate (string filename);        <summary>//////</summary> class DownloadFile {//<summary> Simultaneous download//</summary>//<param name= "FileName" ></param> public string Download ing (string fileName) {string filestr = string.            Empty;            Console.WriteLine ("Download event start execution");            System.Threading.Thread.Sleep (3000);            Random rand = new Random ();            StringBuilder builder =new StringBuilder ();            int num; for (int i=0;i<100;i++) {num = rand.                Next (1000); Builder.            Append (i); } filestr = Builder.            ToString ();            Console.WriteLine ("Download Event execution end");     return filestr;   }///<summary>//Asynchronous download///</summary> public IAsyncResult begindownloading (St Ring fileName) {string filestr = string.            Empty;            Aysndownloaddelegate downloaddelegate = new Aysndownloaddelegate (downloading);        Return Downloaddelegate.begininvoke (fileName, downloaded, downloaddelegate); }///<summary>///Asynchronous download completed event///</summary>//<param name= "Result" ></p aram> private void downloaded (IAsyncResult result) {Aysndownloaddelegate aysndelegate = Resul            T.asyncstate as Aysndownloaddelegate;                if (aysndelegate! = null) {string filestr = Aysndelegate.endinvoke (result); if (!string.                IsNullOrEmpty (FILESTR)) {Console.WriteLine ("Download file: {0}", FILESTR);  } else {Console.WriteLine ("Download data is empty!");              }} else {Console.WriteLine ("Download data is empty!"); }        }    }}

Through the case, we found that the use of delegates can be easily implemented asynchronously. In this way, we can customize our own asynchronous operations.

C # Programming Summary (VI) Asynchronous programming

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.