多线程之异步编程: 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(); } } }
以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索异步编程
, windows
, action
, windows store app
, windows编程
, using
, 返回app
, 进度
, #windows编程
runtime用法
,以便于您获取更多的相关知识。