C # Programming Summary (VI) Detailed explanation of asynchronous programming _c# tutorial

Source: Internet
Author: User
Tags message queue rand wrapper

1, what is asynchronous?

Asynchronous operations are typically used to perform tasks that may take longer to complete, such as opening large files, connecting to a remote computer, or querying a database. Asynchronous operations are performed 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 asynchronous method performs 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 is executing. Essence: Asynchronous operation, which starts a new thread, which executes in parallel with the method thread.

3, asynchronous and multithreading differences

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

Simply put: Asynchronous threads are managed by the thread pool, and multithreading allows us to control ourselves, and of course we can use thread pooling in multiple threads.

With the Internet, if you use asynchronous mode to implement, it uses the thread pool for management. When an asynchronous operation is executed, the operation is dropped to a worker thread in the thread pool to complete. When I/O is started, asynchronous will return the worker thread to the thread pool, which means that getting the Web page does not consume any CPU resources. It is not until the asynchronous completes that the page is finished, and asynchronously notifies the thread pool by callback. This shows that the asynchronous pattern, with the help of a thread pool, greatly saves CPU resources.

NOTE: DMA (direct Memory access) directly memory access, as the name suggests DMA function is to allow devices to bypass the processor, directly from memory to read data. Data exchange through direct memory access can almost without loss of CPU resources. In the hardware, the hard disk, network card, sound card, video card and so on have direct memory access function. The asynchronous programming model allows us to take full advantage of the direct memory access of the hardware to release the CPU pressure.

Scenarios for both:

Compute-intensive work, using multithreading.

IO-intensive work, using asynchronous mechanisms.

4. Asynchronous Application

Many aspects of the. NET Framework support asynchronous programming features, including:

1 file io, stream io, socket IO.

2) network.

3 Remote processing channel (HTTP, TCP) and proxy.

4 XML Web Services created using asp.net.

5) asp.net Web forms.

6 Use the MessageQueue class message queue.

The. NET Framework provides two design patterns for asynchronous operations:

1 asynchronous operation using the IAsyncResult object.

2 Use the asynchronous operation of the event.

IAsyncResult Design patterns allow multiple programming models, but are more complex and difficult to learn, providing flexibility that most applications do not require. If possible, class library designers should implement asynchronous methods using the event-driven model. In some cases, the Library designer should also implement a IAsyncResult based model.

Asynchronous operations using the IAsyncResult design pattern are implemented by two methods named begin operation name and end operation name, which start and close the asynchronous 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 calling the begin operation name, the application can continue to execute instructions on the calling thread while the asynchronous operation executes on another thread. Each time the begin operation name is invoked, the application should also call the end action name to obtain the result of the operation. The begin operation name method begins the 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 invoke, and the common language runtime automatically defines the BeginInvoke and EndInvoke methods with the appropriate signature for that delegate.

The IAsyncResult object stores information about an asynchronous operation. 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 Example

Case 1-Read the file

Often reading files is a time-consuming task, especially when reading large files, common uploads and downloads. But we do not want to keep users waiting, users can also do other operations, can make the system has good interactivity. Here we have written a synchronous call and an asynchronous call to illustrate the comparison.

Reading file classes

Using System;
Using System.IO;

Using System.Threading; Namespace Asynsample {class FileReader {///<summary>///cache pool///</summary> private byt
    E[] 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 file///</summary>///<param name= "path" > File path </param>
      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 ("Sync Read file End"); ///<summary>///Asynchronous read file///</summary>///<param name= "path" ></param> public void Asynreadfile (string path) {Console.writel
      INE ("read the file begin asynchronously");
      Execute endread times wrong, FS has been released, note that you cannot use the freed resource in Asynchrony//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 = 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 (1024);

      Change to your own file path
      string path = "C:\\windows\\dai.log";

      Console.WriteLine ("Start reading the file ...");
      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 ( 1000);
      for (int i = 0; i < 10000; i++)
      {
        if (i% 888 = 0)
        {
          Console.WriteLine ("Multiples of 888: {0}", i);
        }
      }
    }
  }
}

Output results:

Sync output:


Asynchronous output:


Results Analysis:

If this is a synchronous read, the current thread reads the file while reading, and waits until the read is complete to perform the following actions

The asynchronous read is created by creating a new thread, reading the file, while the main thread continues to execute. We can open Task Manager to monitor.

Case two--asynchronous operations based on delegates

How do you make a custom object have asynchronous functions when the system takes some classes with asynchronous invocation?

We can use delegates to easily implement Asynchrony.

Speaking of Begininvoke,endinvoke, I had to stop and look at the nature of the Commission. To facilitate understanding of delegates, 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, owning the Begininvoke,endinvoke,invoke three methods. The first two methods can be used in combination to implement an asynchronous invocation. The third method is invoked in a synchronized fashion. 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 delegate///</summary>///<param name= "FileName" ></par
  Am> Public delegate String Aysndownloaddelegate (string fileName);
    <summary>///asynchronous invocation via delegates///</summary> class DownloadFile {///<summary>///synchronous Downloads </summary>///<param name= "filename" ></param> public string downloading (string fileName ) {string filestr = string.
      Empty;
      Console.WriteLine ("Download event begins 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 (String fileName) {string filestr = string.
      Empty;
      Aysndownloaddelegate downloaddelegate = new Aysndownloaddelegate (downloading);
    Return Downloaddelegate.begininvoke (fileName, downloaded, downloaddelegate);
    Event///</summary>///<param name= "result" ></param>///<summary>///Asynchronous download private void downloaded (IAsyncResult result) {aysndownloaddelegate aysndelegate = result.
      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 easily be implemented asynchronously. In this way, we can customize our own asynchronous operation.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.