Multi-thread Asynchronous programming: Classic and up-to-date asynchronous programming models, Async and await

Source: Internet
Author: User

The classic asynchronous Programming model (IAsyncResult)

    • The latest asynchronous programming model (async and await)
    • Convert IAsyncInfo to Task
    • Convert Task to IAsyncInfo



Example
1. Implement a class that supports asynchronous operations using the classic asynchronous programming model (IAsyncResult)
Thread/async/classicasync.cs

/* * Use the classic Asynchronous programming model (IAsyncResult) to implement a class that supports asynchronous operations */using system;using system.collections.generic;using system.linq;using System.text;using system.threading;using system.threading.tasks;namespace xamldemo.thread.async{public class        Classicasync {Private delegate string hellodelegate (string name);        Private Hellodelegate _hellodelegate;        Public Classicasync () {_hellodelegate = new hellodelegate (Hello); private string Hello (string name) {new ManualResetEvent (false).            WaitOne (3000);        Return "Hello:" + name;            }//Begin method Public IAsyncResult Beginrun (string name, AsyncCallback callback, Object state) {        New thread, go to execute Hello () method, callback is callback, state is context return _hellodelegate.begininvoke (name, callback, state);                }//End method public string Endrun (IAsyncResult ar) {if (AR = = null) throw new NullReferenceException ("IASyncresult cannot be null ");        return _hellodelegate.endinvoke (AR); }    }}

Thread/async/classicasyncdemo.xaml

<page    x:class= "XamlDemo.Thread.Async.ClassicAsyncDemo"    xmlns= "http://schemas.microsoft.com/winfx/ 2006/xaml/presentation "    xmlns:x=" Http://schemas.microsoft.com/winfx/2006/xaml "    xmlns:local=" using: XamlDemo.Thread.Async "    xmlns:d=" http://schemas.microsoft.com/expression/blend/2008 "    xmlns:mc="/http/ schemas.openxmlformats.org/markup-compatibility/2006 "    mc:ignorable=" D ">    <grid background=" Transparent ">        <stackpanel margin=" 0 0 0 ">            <textblock name=" lblmsg "fontsize=" 14.667 "/>< C12/><button name= "Btniasyncresult" content= "IAsyncResult Demo" click= "btniasyncresult_click_1" margin= "0 10 0 0"/ >        </StackPanel>    </Grid></Page>

Thread/async/classicasyncdemo.xaml.cs

/* * Demonstrates how to perform asynchronous operations with the classic asynchronous programming model (IASYNCRESULT) * * IAsyncResult-Asynchronous Operation result * asyncstate-context * iscompleted-whether the asynchronous operation is complete * AsyncWaitHandle-Gets the System.Threading.WaitHandle object that waits for the asynchronous operation to complete (by WaitHandle.WaitOne () waiting in the current thread) */using System;usin G windows.ui.xaml;using windows.ui.xaml.controls;namespace xamldemo.thread.async{public sealed partial class ClassicA        syncdemo:page {System.Threading.SynchronizationContext _synccontext; Public Classicasyncdemo () {this.            InitializeComponent ();        Gets the current UI thread _synccontext = System.Threading.SynchronizationContext.Current; private void Btniasyncresult_click_1 (object sender, RoutedEventArgs e) {Classicasync Classicas            Ync = new Classicasync ();            IAsyncResult ar = Classicasync.beginrun ("Webabcd", New AsyncCallback (Callback), classicasync);        Lblmsg.text = "Start execution, complete after 3 seconds";        } private void Callback (IAsyncResult ar) {    Classicasync Classicasync = (classicasync) ar.            asyncstate;            string result = Classicasync.endrun (AR);                _synccontext.post (CTX) = = {Lblmsg.text = result;        }, NULL); }    }}


2. Demonstrates how to perform asynchronous operations with the latest asynchronous programming model (async and await)
Thread/async/newasyncdemo.xaml

<page x:class= "XamlDemo.Thread.Async.NewAsyncDemo" xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/ Presentation "xmlns:x=" Http://schemas.microsoft.com/winfx/2006/xaml "xmlns:local=" Using:XamlDemo.Thread.Async "XM Lns:d= "http://schemas.microsoft.com/expression/blend/2008" xmlns:mc= "http://schemas.openxmlformats.org/ markup-compatibility/2006 "mc:ignorable=" D "> <grid background=" Transparent "> <stackpanel margin=" 0 0 0 "> <textblock name=" lblmsg "fontsize=" 14.667 "/> <button name=" Btntaskwithoutre Turn "content=" executes a Task with no return value "click=" Btntaskwithoutreturn_click_1 "margin=" 0 0 0 "/> <button name=" b  Tntaskwithreturn "Content=" executes a Task with return value "click=" Btntaskwithreturn_click_1 "margin=" 0 0 0 "/> <button Name= "Btnmultitask" content= "parallel execution of multiple tasks" click= "Btnmultitask_click_1" margin= "0 0 0"/> <button Name = "Btntaskwithoutawait" content= "executes a Task that does not await"click=" Btntaskwithoutawait_click_1 "margin=" 0 0 0 "/> </StackPanel> </Grid></Page> 

Thread/async/newasyncdemo.xaml.cs

/* * Demonstrates how to perform asynchronous operations with the latest asynchronous programming model (Async and await) * Note: * 1. To await, its method must be marked as Async * 2, the method is marked as async in order for the compiler to rewrite the method so that the await The content is rewritten as code with actual asynchronous logic such as Getawaiter () */using system;using system.threading;using system.threading.tasks;using Windows.ui.xaml;using windows.ui.xaml.controls;namespace xamldemo.thread.async{public sealed partial class        newasyncdemo:page {private static int _count = 0; Public Newasyncdemo () {this.        InitializeComponent (); }//Task with no return value the private async task Taskwithoutreturn () {//sleep in another thread for 1000 milliseconds, then back to UI            Thread await task.delay (1000); Await Task.delay (timeout.infinite); Resting in this//await Task.delay (Timeout.infinitetimespan); Sleep here//directly in the current thread sleep can use the following method, because WinRT does not have thread.sleep ()//new ManualResetEvent (FALSE).            WaitOne (1000);        Interlocked.Increment (ref _count); }//Task private async TASK&LT;INT&G with return valueT            Taskwithreturn () {await task.delay (1000);            Interlocked.Increment (ref _count);        return _count;             }//Demo asynchronous operation without return value private async void Btntaskwithoutreturn_click_1 (object sender, RoutedEventArgs e) { Configureawait (false)-does not return the UI thread after an asynchronous operation, saving a bit of resources. Default value: Configureawait (True) await Taskwithoutreturn ().            Configureawait (FALSE); Lblmsg.text = "Count:" + _count.        ToString ();            }//Demo asynchronous operation with return value private async void Btntaskwithreturn_click_1 (object sender, RoutedEventArgs e) {            int result = await taskwithreturn (); Lblmsg.text = "Count:" + result.        ToString ();            }//demonstrates asynchronous operations in parallel execution of multitasking private async void Btnmultitask_click_1 (object sender, RoutedEventArgs e) {            Task task = Task.whenall (Taskwithoutreturn (), Taskwithoutreturn (), Taskwithoutreturn ());            DateTime dt = DateTime.Now;            await task; Lblmsg. Text = "Count:" + _count. ToString () + ", Execution Time:" + (DATETIME.NOW-DT).        Totalseconds.tostring () + "seconds";        }//Demonstrates how to execute a non-await Task private void Btntaskwithoutawait_click_1 (object sender, RoutedEventArgs e)            {//Let the task execute in a new thread, this thread no matter what the execution of the task task = Taskwithoutreturn (); Lblmsg.text = "Count:" + _count.        ToString (); }    }}


3. Demonstrates how to turn IAsyncInfo (iasyncaction, Iasyncoperation, iasyncactionwithprogress, iasyncoperationwithprogress) into a Task
Thread/async/iasyncinfo2task.xaml

<page    x:class= "XamlDemo.Thread.Async.IAsyncInfo2Task"    xmlns= "http://schemas.microsoft.com/winfx/ 2006/xaml/presentation "    xmlns:x=" Http://schemas.microsoft.com/winfx/2006/xaml "    xmlns:local=" using: XamlDemo.Thread.Async "    xmlns:d=" http://schemas.microsoft.com/expression/blend/2008 "    xmlns:mc="/http/ schemas.openxmlformats.org/markup-compatibility/2006 "    mc:ignorable=" D ">    <grid background=" Transparent ">        <stackpanel margin=" 0 0 0 ">            <textblock name=" lblmsg "fontsize=" 14.667 "/>< C12/></stackpanel>    </Grid></Page>

Thread/async/iasyncinfo2task.xaml.cs

/* * Demonstrates how to turn IAsyncInfo (iasyncaction, Iasyncoperation, iasyncactionwithprogress, iasyncoperationwithprogress) into a Task */ Using system;using system.runtime.interopservices.windowsruntime;using system.threading;using System.threading.tasks;using windows.foundation;using windows.ui.xaml.controls;using Windows.UI.Xaml.Navigation; namespace xamldemo.thread.async{public sealed partial class Iasyncinfo2task:page {public Iasyncinfo2task ( ) {this.        InitializeComponent (); } protected async override void Onnavigatedto (NavigationEventArgs e) {//used to cancel a Task Ca            Ncellationtokensource cts = new CancellationTokenSource ();                   Create a IAsyncInfo iasyncoperation<int> action = asyncinfo.run<int> (token) = = Task.run<int> (() = {Toke                           N.waithandle.waitone (3000); Token. THrowifcancellationrequested ();                       return 10 * 10;            }, token));            Lblmsg.text = "Start execution, complete after 3 seconds"; Converting iasyncoperation to Task//AsTask () is an extension method whose logic is in the System.windowsruntimesystemextensions class TASK&L t;int> task = action. Astask<int> (CTS.            Token);            int result = await task; Lblmsg.text = "Result:" + result.        ToString (); }    }}


4. Demonstrates how to turn a Task into IAsyncInfo (iasyncaction, iasyncoperation)
Thread/async/task2iasyncinfo.xaml

<page    x:class= "XamlDemo.Thread.Async.Task2IAsyncInfo"    xmlns= "http://schemas.microsoft.com/winfx/ 2006/xaml/presentation "    xmlns:x=" Http://schemas.microsoft.com/winfx/2006/xaml "    xmlns:local=" using: XamlDemo.Thread.Async "    xmlns:d=" http://schemas.microsoft.com/expression/blend/2008 "    xmlns:mc="/http/ schemas.openxmlformats.org/markup-compatibility/2006 "    mc:ignorable=" D ">    <grid background=" Transparent ">        <stackpanel margin=" 0 0 0 ">            <textblock name=" lblmsg "fontsize=" 14.667 "/>< C12/></stackpanel>    </Grid></Page>

Thread/async/task2iasyncinfo.xaml.cs

/* * Demonstrates how to turn a Task into IAsyncInfo (iasyncaction, iasyncoperation) */using system;using system.threading;using System.threading.tasks;using windows.foundation;using windows.ui.xaml.controls;using Windows.UI.Xaml.Navigation; namespace xamldemo.thread.async{public sealed partial class Task2iasyncinfo:page {public Task2iasyncinfo ( ) {this.        InitializeComponent ();  } protected async override void Onnavigatedto (NavigationEventArgs e) {//For canceling IAsyncInfo (note: In this example IAsyncInfo is converted from a Task, so the Iasyncinfo.cancel () method is invalid) CancellationTokenSource cts = new CANCELLATIONTOKENSOURC            E ();                    Create a task task<int> task = task.run<int> (() + = { Cts.                    Token.WaitHandle.WaitOne (3000); Cts.                    Token.throwifcancellationrequested ();                return 10 * 10; }, CTS.            Token); Lblmsg.text = "Start execution, complete after 3 seconds";            Converting a Task to Iasyncoperation//Asasyncaction (), Asasyncoperation () is an extension method whose logic is in the System.windowsrunti iasyncoperation<int> operation = Task in the Mesystemextensions class.            Asasyncoperation<int> ();            int result = await operation; Lblmsg.text = "Result:" + result.                   ToString (); }    }}

Multi-thread Asynchronous programming: Classic and up-to-date asynchronous programming models, Async and await

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.