Three kinds of asynchronous programming model

Net lot of class interface design when they are considered multi-threading issues, simplifying the development of multi-threaded programs. You do not have to write their own WaitHandler these underlying code, etc. Because of the historical development, interface design these classes has three different styles: EAP (*) ,
APM (*) and TPL . Currently the focus with TPL .

 

EAP


EAP is the Event-based Asynchronous Pattern (event-based asynchronous model) shorthand, similar to Ajax in the XmlHttpRequest , the send after processing is not finished, but onreadystatechange event notification process is complete again.

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }    

        private void button1_Click(object sender, EventArgs e)
        {
         
            WebClient client = new WebClient();
            client.DownloadStringCompleted += Client_DownloadStringCompleted;
            client.DownloadStringAsync(new Uri("http://www.baidu.com")); ;

        }

        private void Client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            MessageBox.Show(e.Result);
        }
    }

The advantage is simple, the disadvantage is when implementing complex business when a lot of trouble, such as downloading A after a successful download b , if the download b successful re-download c , otherwise download d .
EAP characteristics of the class are: an asynchronous method with a Completed *** event. .Net -based EAP little analogy. There are better alternatives, so you can understand.

 

AMP


APM (Asynchronous Programming Model) is a .Net asynchronous programming model widely used in older versions. Use the APM asynchronous method returns an IAsyncResult object that has an important property of the AsyncWaitHandle , he is
to wait for a synchronous signal asynchronous task execution ended.

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            FileStream fs = File.OpenRead("d:/1.txt");
            byte[] buffer = new byte[16];
            IAsyncResult aResult = fs.BeginRead(buffer, 0, buffer.Length, null, null);
            aResult.AsyncWaitHandle.WaitOne (); // wait for task execution ends 
            MessageBox.Show (Encoding.UTF8.GetString (Buffer)); 
            fs.EndRead (aResult); 
        } 
    }

If not aResult.AsyncWaitHandle.WaitOne () it is likely to print a blank, because BeginRead only "start reading." To call a general call to complete EndXXX to recover resources. APM is characterized by: a method name to BeginXXX beginning, return type IAsyncResult , after the call needs EndXXX .
.Net in the following commonly used class supports the APM : Stream , the SqlCommand , the Socket like.
APM is still too complicated, you can understand.

 

TPL


TPL ( Task Parallel Library ) is a .Net 4.0 brings the following new features, more concise, more convenient. Now in .Net it has a large area under the platform.

  private void button1_Click(object sender, EventArgs e)
        {
            FileStream fs = File.OpenRead("d:/1.txt");
            byte[] buffer = new byte[16];
            Task<int> task = fs.ReadAsync(buffer, 0, buffer.Length);
            task.Wait();
            MessageBox.Show("读取了" + task.Result + "个字节");
            MessageBox.Show(Encoding.UTF8.GetString(buffer));
        }

Use the keyword async and awit

 private async void button2_Click(object sender, EventArgs e)
        {
            FileStream fs = File.OpenRead("d:/1.txt");
            byte[] buffer = new byte[16];
            int len = await fs.ReadAsync(buffer, 0, buffer.Length);
            MessageBox.Show("读取了" + len + "个字节");
            MessageBox.Show(Encoding.UTF8.GetString(buffer));
        }

Note that if there is method in the await , the method must be marked as the async , not all methods can be easily marked as the async . WinForm event handling methods can be labeled as the async , MVC in Action method can also be marked as the async , the console's Main method can not be labeled as the async .
TPL is characterized by: methods in XXXAsync end, the return value is the generic type the Task <T> .
TPL allows us to use a linear way to write asynchronous program is no longer needed as EAP , as do a bunch of callbacks, the logical jumping up. await now been JavaScript draw away!

 


With await achieve "to download A , if the downloaded content length greater than 100 is downloaded B , or download C " is very easy to
look at WebClient the TPL usage:

Private  the async  void the button3_Click ( Object SENDER, EventArgs E) 
        { 
            var WC = new new the WebClient ();
             String HTML = the await wc.DownloadStringTaskAsync ( " http://www.baidu.com " ); // do not lose the await 
            MessageBox.Show (HTML);
             // the above code is not fully equivalent to 
            the WebClient WC1 = new new the WebClient ();
             var Task wc1.DownloadStringTaskAsync = ( " http://www.baidu.com " ); 
            task.Wait ();
            MessageBox.Show (task.Result); 

            //   because if the wording in accordance with the above, will get stuck on the UI thread
             // and await does not. . . seems not? ? ? It was only because the html such a long string
             // MessageBox.Show very slow, MessageBox.Show (html.Substring (10)) ; to prove this point 


            // Task <T> T What type of each method not the same, depending on the document.
            // WebClient, Stream, such as the Socket these "historic" in class while providing APM, TPL-style
             // API, and even some also provide EAP-style API. Whenever possible, use TPL-style 
        }

Writing asynchronous method

Return value Task <T>, unspoken rules (not required) Async method name to the end:

 static Task<string> F2Async()
        {
            return Task.Run(() =>
            {
                System.Threading.Thread.Sleep(2000);
                return "F2";
            });
        }

transfer

 private async void button4_Click(object sender, EventArgs e)
        {
            string s = await F2Async();
            MessageBox.Show(s);

        }

 

Guess you like

Origin www.cnblogs.com/Jenkin/p/12048748.html