多線程之非同步編程: 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
<Page x: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 建立 IAsyncAction return AsyncInfo.Run( (token) => // CancellationToken token Task.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, Error lblMsg.Text = "完成了,AsyncStatus: " + asyncStatus.ToString(); }; lblMsg.Text = "開始執行,3 秒後完成"; } // 取消 IAsyncAction private void btnCancelAsyncAction_Click_1(object sender, RoutedEventArgs e) { if (_action != null) _action.Cancel(); } }}