重新想象 Windows 8 Store Apps (45) - 多线程之异步编程: IAsyncAction, IAsyncOperation, IAsyncActionWithProgress, IAsyncOperationWithProgress

简介: 原文:重新想象 Windows 8 Store Apps (45) - 多线程之异步编程: IAsyncAction, IAsyncOperation, IAsyncActionWithProgress, IAsyncOperationWithProgress[源码下载] 重新想象 Window...
原文: 重新想象 Windows 8 Store Apps (45) - 多线程之异步编程: IAsyncAction, IAsyncOperation, IAsyncActionWithProgress, IAsyncOperationWithProgress

[源码下载]


重新想象 Windows 8 Store Apps (45) - 多线程之异步编程: IAsyncAction, IAsyncOperation, IAsyncActionWithProgress, IAsyncOperationWithProgress



作者:webabcd


介绍
重新想象 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();
        }
    }
}


2、演示 IAsyncOperation<TResult>(有返回值,无进度值)的用法
Thread/Async/IAsyncOperationDemo.xaml

<Page
    x:Class="XamlDemo.Thread.Async.IAsyncOperationDemo"
    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="btnCreateAsyncOperation" Content="执行一个 IAsyncOperation" Click="btnCreateAsyncOperation_Click_1" Margin="0 10 0 0" />

            <Button Name="btnCancelAsyncOperation" Content="取消" Click="btnCancelAsyncOperation_Click_1" Margin="0 10 0 0" />

        </StackPanel>
    </Grid>
</Page>

Thread/Async/IAsyncOperationDemo.xaml.cs

/*
 * 演示 IAsyncOperation<TResult>(有返回值,无进度值)的用法
 * 
 * 注:
 * 1、WinRT 中的异步功能均源自 IAsyncInfo
 * 2、IAsyncAction, IAsyncOperation<TResult>, IAsyncActionWithProgress<TProgress>, IAsyncOperationWithProgress<TResult, TProgress> 均继承自 IAsyncInfo
 */

using System;
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 IAsyncOperationDemo : Page
    {
        private IAsyncOperation<int> _operation;

        public IAsyncOperationDemo()
        {
            this.InitializeComponent();
        }

        private IAsyncOperation<int> GetAsyncOperation(int x, int y)
        {
            // 通过 System.Runtime.InteropServices.WindowsRuntime.AsyncInfo 创建 IAsyncOperation<TResult>
            return AsyncInfo.Run<int>(
               (token) => // CancellationToken token
                   Task.Run<int>(
                       () =>
                       {
                           token.WaitHandle.WaitOne(3000);
                           token.ThrowIfCancellationRequested();

                           // 返回结果
                           return x * y;
                       },
                       token));
        }

        private void btnCreateAsyncOperation_Click_1(object sender, RoutedEventArgs e)
        {
            _operation = GetAsyncOperation(10, 10);

            // 可以 await _operation 

            // IAsyncOperation<TResult> 完成后
            _operation.Completed =
                (asyncInfo, asyncStatus) => // IAsyncAction asyncInfo, AsyncStatus asyncStatus
                {
                    // AsyncStatus 包括:Started, Completed, Canceled, Error
                    lblMsg.Text = "完成了,AsyncStatus: " + asyncStatus.ToString();

                    if (asyncStatus == AsyncStatus.Completed)
                    {
                        lblMsg.Text += Environment.NewLine;
                        // 获取异步操作的返回结果
                        lblMsg.Text += "结果: " + asyncInfo.GetResults().ToString();
                    }
                };

            lblMsg.Text = "开始执行,3 秒后完成";
        }

        // 取消 IAsyncOperation<TResult>
        private void btnCancelAsyncOperation_Click_1(object sender, RoutedEventArgs e)
        {
            if (_operation != null)
                _operation.Cancel();
        }
    }
}


3、演示 IAsyncActionWithProgress<TProgress>(无返回值,有进度值)的用法
Thread/Async/IAsyncActionWithProgressDemo.xaml

<Page
    x:Class="XamlDemo.Thread.Async.IAsyncActionWithProgressDemo"
    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" />
            <TextBlock Name="lblProgress" FontSize="14.667" />

            <Button Name="btnCreateAsyncActionWithProgress" Content="执行一个 IAsyncActionWithProgress" Click="btnCreateAsyncActionWithProgress_Click_1" Margin="0 10 0 0" />

            <Button Name="btnCancelAsyncActionWithProgress" Content="取消" Click="btnCancelAsyncActionWithProgress_Click_1" Margin="0 10 0 0" />

        </StackPanel>
    </Grid>
</Page>

Thread/Async/IAsyncActionWithProgressDemo.xaml.cs

/*
 * 演示 IAsyncActionWithProgress<TProgress>(无返回值,有进度值)的用法
 * 
 * 注:
 * 1、WinRT 中的异步功能均源自 IAsyncInfo
 * 2、IAsyncAction, IAsyncOperation<TResult>, IAsyncActionWithProgress<TProgress>, IAsyncOperationWithProgress<TResult, TProgress> 均继承自 IAsyncInfo
 */

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 IAsyncActionWithProgressDemo : Page
    {
        private IAsyncActionWithProgress<int> _action;

        public IAsyncActionWithProgressDemo()
        {
            this.InitializeComponent();
        }

        private IAsyncActionWithProgress<int> GetAsyncActionWithProgress()
        {
            // 通过 System.Runtime.InteropServices.WindowsRuntime.AsyncInfo 创建 IAsyncActionWithProgress<TProgress>
            return AsyncInfo.Run<int>(
                (token, progress) => // CancellationToken token, IProgress<TProgress> progress
                    Task.Run(
                        () =>
                        {
                            // 报告进度(进度是一个 int 值)
                            progress.Report(0);

                            int percent = 0;
                            while (percent < 100)
                            {
                                token.WaitHandle.WaitOne(100);
                                token.ThrowIfCancellationRequested();

                                percent++;

                                // 报告进度(进度是一个 int 值)
                                progress.Report(percent);
                            }
                        },
                        token));
        }

        private void btnCreateAsyncActionWithProgress_Click_1(object sender, RoutedEventArgs e)
        {
            _action = GetAsyncActionWithProgress();

            // 可以 await _action 

            // IAsyncActionWithProgress<TProgress> 完成后
            _action.Completed =
                (asyncInfo, asyncStatus) => // IAsyncAction asyncInfo, AsyncStatus asyncStatus
                {
                    // AsyncStatus 包括:Started, Completed, Canceled, Error
                    lblMsg.Text = "完成了,AsyncStatus: " + asyncStatus.ToString();
                };

            // IAsyncActionWithProgress<TProgress> 接收到进度后
            _action.Progress =
                (asyncInfo, progressInfo) => // IAsyncActionWithProgress<TProgress> asyncInfo, TProgress progressInfo
                {
                    // 进度是一个 int 值
                    lblProgress.Text = "进度: " + progressInfo.ToString();
                };

            lblMsg.Text = "开始执行";
        }

        // 取消 IAsyncActionWithProgress<TProgress>
        private void btnCancelAsyncActionWithProgress_Click_1(object sender, RoutedEventArgs e)
        {
            if (_action != null)
                _action.Cancel();
        }
    }
}


4、演示 IAsyncOperationWithProgress<TResult, TProgress>(有返回值,有进度值)的用法
Thread/Async/IAsyncOperationWithProgressDemo.xaml

<Page
    x:Class="XamlDemo.Thread.Async.IAsyncOperationWithProgressDemo"
    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" />
            <TextBlock Name="lblProgress" FontSize="14.667" />

            <Button Name="btnCreateAsyncOperationWithProgress" Content="执行一个 IAsyncOperationWithProgress" Click="btnCreateAsyncOperationWithProgress_Click_1" Margin="0 10 0 0" />

            <Button Name="btnCancelAsyncOperationWithProgress" Content="取消" Click="btnCancelAsyncOperationWithProgress_Click_1" Margin="0 10 0 0" />

        </StackPanel>
    </Grid>
</Page>

Thread/Async/IAsyncOperationWithProgressDemo.xaml.cs

/*
 * 演示 IAsyncOperationWithProgress<TResult, TProgress>(有返回值,有进度值)的用法
 * 
 * 注:
 * 1、WinRT 中的异步功能均源自 IAsyncInfo
 * 2、IAsyncAction, IAsyncOperation<TResult>, IAsyncActionWithProgress<TProgress>, IAsyncOperationWithProgress<TResult, TProgress> 均继承自 IAsyncInfo
 * 
 * 
 * 另:
 * Windows.Web.Syndication.SyndicationClient.RetrieveFeedAsync() - 返回的就是 IAsyncOperationWithProgress<TResult, TProgress>
 */

using System;
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 IAsyncOperationWithProgressDemo : Page
    {
        private IAsyncOperationWithProgress<string, int> _operation;

        public IAsyncOperationWithProgressDemo()
        {
            this.InitializeComponent();
        }

        private IAsyncOperationWithProgress<string, int> GetAsyncOperationWithProgress()
        {
            // 通过 System.Runtime.InteropServices.WindowsRuntime.AsyncInfo 创建 IAsyncOperationWithProgress<TResult, TProgress>
            return AsyncInfo.Run<string, int>(
                (token, progress) =>
                    Task.Run<string>(
                        () =>
                        {
                            // 报告进度(进度是一个 int 值)
                            progress.Report(0);

                            int percent = 0;
                            while (percent < 100)
                            {
                                token.WaitHandle.WaitOne(100);
                                token.ThrowIfCancellationRequested();

                                percent++;

                                // 报告进度(进度是一个 int 值)
                                progress.Report(percent);
                            }

                            // 返回结果
                            return "成功了";
                        },
                        token));
        }

        private void btnCreateAsyncOperationWithProgress_Click_1(object sender, RoutedEventArgs e)
        {
            _operation = GetAsyncOperationWithProgress();

            // 可以 await _operation 

            // IAsyncOperationWithProgress<TResult, TProgress> 完成后
            _operation.Completed =
                (asyncInfo, asyncStatus) => // IAsyncAction asyncInfo, AsyncStatus asyncStatus
                {
                    // AsyncStatus 包括:Started, Completed, Canceled, Error
                    lblMsg.Text = "完成了,AsyncStatus: " + asyncStatus.ToString();

                    if (asyncStatus == AsyncStatus.Completed)
                    {
                        lblMsg.Text += Environment.NewLine;
                        // 获取异步操作的返回结果
                        lblMsg.Text += "结果: " + asyncInfo.GetResults().ToString();
                    }
                };

            // IAsyncOperationWithProgress<TResult, TProgress> 接收到进度后
            _operation.Progress =
                (asyncInfo, progressInfo) => // IAsyncActionWithProgress<TProgress> asyncInfo, TProgress progressInfo
                {
                    // 进度是一个 int 值
                    lblProgress.Text = "进度: " + progressInfo.ToString();
                };

            lblMsg.Text = "开始执行";
        }

        // 取消 IAsyncOperationWithProgress<TResult, TProgress>
        private void btnCancelAsyncOperationWithProgress_Click_1(object sender, RoutedEventArgs e)
        {
            if (_operation != null)
                _operation.Cancel();
        }
    }
}



OK
[源码下载]

目录
相关文章
|
Linux C++ Windows
【Azure 应用服务】Azure App Service(Windows)环境中如何让.NET应用调用SAP NetWeaver RFC函数
【Azure 应用服务】Azure App Service(Windows)环境中如何让.NET应用调用SAP NetWeaver RFC函数
531 0
【Azure 应用服务】Azure App Service(Windows)环境中如何让.NET应用调用SAP NetWeaver RFC函数
|
Java 数据库 Android开发
一个Android App最少有几个线程?实现多线程的方式有哪些?
本文介绍了Android多线程编程的重要性及其实现方法,涵盖了基本概念、常见线程类型(如主线程、工作线程)以及多种多线程实现方式(如`Thread`、`HandlerThread`、`Executors`、Kotlin协程等)。通过合理的多线程管理,可大幅提升应用性能和用户体验。
860 15
一个Android App最少有几个线程?实现多线程的方式有哪些?
|
C# Windows
【Azure App Service】在App Service for Windows上验证能占用的内存最大值
根据以上测验,当使用App Service内存没有达到预期的值,且应用异常日志出现OutOfMemory时,就需要检查Platform的设置是否位64bit。
470 11
|
Java 数据库 Android开发
一个Android App最少有几个线程?实现多线程的方式有哪些?
本文介绍了Android应用开发中的多线程编程,涵盖基本概念、常见实现方式及最佳实践。主要内容包括主线程与工作线程的作用、多线程的多种实现方法(如 `Thread`、`HandlerThread`、`Executors` 和 Kotlin 协程),以及如何避免内存泄漏和合理使用线程池。通过有效的多线程管理,可以显著提升应用性能和用户体验。
633 11
|
Java 应用服务中间件 开发工具
[App Service for Windows]通过 KUDU 查看 Tomcat 配置信息
[App Service for Windows]通过 KUDU 查看 Tomcat 配置信息
361 2
|
Java 应用服务中间件 Windows
【App Service for Windows】为 App Service 配置自定义 Tomcat 环境
【App Service for Windows】为 App Service 配置自定义 Tomcat 环境
317 2
|
PHP Windows
【Azure App Service for Windows】 PHP应用出现500 : The page cannot be displayed because an internal server error has occurred. 错误
【Azure App Service for Windows】 PHP应用出现500 : The page cannot be displayed because an internal server error has occurred. 错误
452 1
|
网络安全 API 数据安全/隐私保护
【Azure App Service】.NET代码实验App Service应用中获取TLS/SSL 证书 (App Service Windows)
【Azure App Service】.NET代码实验App Service应用中获取TLS/SSL 证书 (App Service Windows)
362 0
|
Shell PHP Windows
【Azure App Service】Web Job 报错 UNC paths are not supported. Defaulting to Windows directory.
【Azure App Service】Web Job 报错 UNC paths are not supported. Defaulting to Windows directory.
394 0
|
存储 Linux Windows
【应用服务 App Service】App Service For Windows 如何挂载Storage Account File Share 示例
【应用服务 App Service】App Service For Windows 如何挂载Storage Account File Share 示例
286 0

热门文章

最新文章