Windows 8 Store Apps学习(45) 多线程之异步编程: IAsyncAction2013-12-10 cnblogs webabcd多线程之异步编程: IAsyncAction, IAsyncOperation重新想象 Windows 8 Store Apps (45) - 多线程之异步编程: IAsyncAction, IAsyncOperation, IAsyncActionWithProgress, IAsyncOperationWithProgress介绍重新想象 Windows 8 Store Apps 之 异步编程IAsyncAction - 无返回值,无进度值IAsyncOperation - 有返回值,无进度值IAsyncActionWithProgress - 无返回值,有进度值IAsyncOperationWithProgress - 有返回 值,有进度值示例1、演示 IAsyncAction(无返回值,无进度值)的用法Thread/Async/IAsyncActionDemo.xaml
<Pagex:Class="XamlDemo.Thread.Async.IAsyncActionDemo"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="btnCreateAsyncAction" Content="执行一个 IAsyncAction" Click="btnCreateAsyncAction_Click_1" Margin="0 10 0 0" /><Button Name="btnCancelAsyncAction" Content="取消" Click="btnCancelAsyncAction_Click_1" Margin="0 10 0 0" /></StackPanel></Grid></Page>
Thread/Async/IAsyncActionDemo.xaml.cs
/* * 演示 IAsyncAction(无返回值,无进度值)的用法 ** 注: * 1、WinRT 中的异步功能均源自 IAsyncInfo * 2、IAsyncAction, IAsyncOperation<TResult>, IAsyncActionWithProgress<TProgress>, IAsyncOperationWithProgress<TResult, TProgress> 均继承自 IAsyncInfo *** 另: * Windows.System.Threading.ThreadPool.RunAsync() - 返回的就是 IAsyncAction */using System.Runtime.InteropServices.WindowsRuntime;using System.Threading.Tasks;using Windows.Foundation;using Windows.UI.Xaml;using Windows.UI.Xaml.Controls;namespace XamlDemo.Thread.Async{public sealed partial class IAsyncActionDemo : Page{private IAsyncAction _action;public IAsyncActionDemo(){this.InitializeComponent();}private IAsyncAction GetAsyncAction(){// 通过 System.Runtime.InteropServices.WindowsRuntime.AsyncInfo 创建 IAsyncActionreturn AsyncInfo.Run((token) => // CancellationToken tokenTask.Run(() =>{token.WaitHandle.WaitOne(3000);token.ThrowIfCancellationRequested();},token));}private void btnCreateAsyncAction_Click_1(object sender, RoutedEventArgs e){_action = GetAsyncAction();// 可以 await _action // IAsyncAction 完成后_action.Completed =(asyncInfo, asyncStatus) => // IAsyncAction asyncInfo, AsyncStatus asyncStatus{// AsyncStatus 包括:Started, Completed, Canceled, ErrorlblMsg.Text = "完成了,AsyncStatus: " + asyncStatus.ToString();};lblMsg.Text = "开始执行,3 秒后完成";}// 取消 IAsyncActionprivate void btnCancelAsyncAction_Click_1(object sender, RoutedEventArgs e){if (_action != null)_action.Cancel();}}}