Windows 8 Store Apps學習(44) 多線程之非同步編程

來源:互聯網
上載者:User

多線程之非同步編程: 經典和最新的非同步編程模型, IAsyncInfo 與 Task 相互轉換

介紹

重新想象 Windows 8 Store Apps 之 非同步編程

經典的非同步編程模型(IAsyncResult)

最新的非同步編程模型(async 和 await)

將 IAsyncInfo 轉換成 Task

將 Task 轉換成 IAsyncInfo

樣本

1、使用經典的非同步編程模型(IAsyncResult)實現一個支援非同步作業的類

Thread/Async/ClassicAsync.cs

/* * 使用經典的非同步編程模型(IAsyncResult)實現一個支援非同步作業的類 */    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 方法        public IAsyncResult BeginRun(string name, AsyncCallback callback, Object state)        {            // 新開線程,去執行 Hello() 方法,callback 是回調,state 是上下文            return _helloDelegate.BeginInvoke(name, callback, state);        }            // end 方法        public string EndRun(IAsyncResult ar)        {            if (ar == null)                throw new NullReferenceException("IAsyncResult 不能為 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="120 0 0 0">                <TextBlock Name="lblMsg" FontSize="14.667" />                <Button Name="btnIAsyncResult" Content="IAsyncResult 的 Demo" Click="btnIAsyncResult_Click_1" Margin="0 10 0 0" />            </StackPanel>    </Grid></Page>

Thread/Async/ClassicAsyncDemo.xaml.cs

/* * 示範如何通過經典的非同步編程模型(IAsyncResult)來進行非同步作業 *  * IAsyncResult - 非同步作業結果 *     AsyncState - 上下文 *     IsCompleted - 非同步作業是否已完成 *     AsyncWaitHandle -  擷取用於等待非同步作業完成的 System.Threading.WaitHandle 對象(通過WaitHandle.WaitOne() 在當前線程等待) */    using System;using Windows.UI.Xaml;using Windows.UI.Xaml.Controls;    namespace XamlDemo.Thread.Async{    public sealed partial class ClassicAsyncDemo : Page    {        System.Threading.SynchronizationContext _syncContext;            public ClassicAsyncDemo()        {            this.InitializeComponent();                // 擷取當前 UI 線程            _syncContext = System.Threading.SynchronizationContext.Current;        }            private void btnIAsyncResult_Click_1(object sender, RoutedEventArgs e)        {            ClassicAsync classicAsync = new ClassicAsync();                IAsyncResult ar = classicAsync.BeginRun("webabcd", new AsyncCallback(Callback), classicAsync);                lblMsg.Text = "開始執行,3 秒後完成";        }            private void Callback(IAsyncResult ar)        {            ClassicAsync classicAsync = (ClassicAsync)ar.AsyncState;            string result = classicAsync.EndRun(ar);                _syncContext.Post(                (ctx) =>                {                    lblMsg.Text = result;                },                null);        }    }}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.