Asynchronous Programming C # callback method

Source: Internet
Author: User

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.

usingSystem;usingSystem.IO;usingSystem.Threading;namespaceasynsample{classFileReader {/// <summary>        ///Cache Pool/// </summary>        Private byte[] Buffer {Get;Set; } /// <summary>        ///Buffer size/// </summary>         Public intbuffersize {Get;Set; }  PublicFileReader (intbuffersize) {             This. BufferSize =buffersize;  This. Buffer =New byte[buffersize]; }        /// <summary>        ///Read files synchronously/// </summary>        /// <param name= "path" >file path</param>         Public voidSynsreadfile (stringpath) {Console.WriteLine ("read files synchronously begin"); using(FileStream fs =NewFileStream (path, FileMode.Open)) {fs. Read (Buffer,0, buffersize); stringOutput =System.Text.Encoding.UTF8.GetString (Buffer); Console.WriteLine ("Read file information: {0}", output); } Console.WriteLine ("Synchronize read file end"); }        /// <summary>        ///Read files asynchronously/// </summary>        /// <param name= "path" ></param>         Public voidAsynreadfile (stringpath) {Console.WriteLine ("read file asynchronously begin"); //Execute endread times error, FS has been freed, note that freeing the required resources is not available in async//using (FileStream fs = new FileStream (path, FileMode.Open))//{            //Buffer = new Byte[buffersize]; //FS.            BeginRead (Buffer, 0, buffersize, Asyncreadcallback, FS); //}             if(file.exists (path)) {FileStream fs=NewFileStream (path, FileMode.Open); Fs. BeginRead (Buffer,0, buffersize, Asyncreadcallback, FS); }            Else{Console.WriteLine ("The file does not exist"); }        }        /// <summary>        ///         /// </summary>        /// <param name= "ar" ></param>        voidasyncreadcallback (IAsyncResult ar) {FileStream stream= Ar. AsyncState asFileStream; if(Stream! =NULL) {Thread.Sleep ( +); //Read EndStream.                EndRead (AR); Stream.                Close (); stringOutput = System.Text.Encoding.UTF8.GetString ( This.                Buffer); Console.WriteLine ("Read file information: {0}", output); }        }    }}

Test Cases

usingSystem;usingSystem.Threading;namespaceasynsample{classProgram {Static voidMain (string[] args) {FileReader Reader=NewFileReader (1024x768); //change to your own file path            stringPath ="C:\\windows\\dai.log"; Console.WriteLine ("start reading the file ..."); //Reader. Synsreadfile (path);Reader.            Asynreadfile (path); Console.WriteLine ("I still have a big beach here.");            DoSomething (); Console.WriteLine ("finally finished, enter any key, rest! ");                   Console.readkey (); }        /// <summary>        ///         /// </summary>        Static voiddosomething () {Thread.Sleep ( +);  for(inti =0; I <10000; i++)            {                ifI888==0) {Console.WriteLine ("multiples of 888: {0}", i); }            }        }    }}

Asynchronous Programming C # callback method

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.