Windows 8 学习笔记(十七)--.WinRT 异步编程

我们知道,在WinRT中很多接口都是异步的,如StorageFileMediaCapture等。它们都是以“Async”结尾。那使用异步编程有什么好处呢?估计大家都知道,当我们执行一个函数需要花费数秒钟,若使用同步方法,则会阻止UI线程,应用将不会响应用户操作,体验性将会非常糟糕。而使用异步编程,应用在等待完成时可以继续运行并响应UI

WinRT中,每种语言都有其异步编程的模式:

JavaScript :   承诺对象,then函数

C#:  将来对象,await运算符

VB:  将来对象,await运算符

Visual C++:  task类,.then方法

WinRT 异步编程(C#

WinRT中的C#异步编程相对较简单,需要遵守几个规则:

(1)      调用异步API的方法体前需要以async标识

(2)      调用异步API需要使用await运算符

Await运算符你可将其看作它告诉编译器当前正在调用某个异步方法,编译器可以执行其它的工作,无需在此等待。作用await运算符的好处是代码看上去不复杂,又易于理解和维护。

private async void CreateFile()
        {
            StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
            StorageFile storageFile = await storageFolder.CreateFileAsync("template.txt",CreationCollisionOption.ReplaceExisting);
            OutputTextBlock.Text = storageFolder.Name + "has been created"

              }

 

 WinRT 异步编程(C++

C++异步编程相对C#较复杂些,主要通过ppltask.h中定义的任务类来使用异步方法。

C++中直接使用异步WinRT API时,首选task类及其相关类型和函数,它们都包含在concurrency命名空间中,并且在ppltask.h中定义。

(1)      利用create_task创建一个任务

auto createFileTadk =create_task(folder->CreateFileAsync("aa.txt",CreationCollisionOption::ReplaceExisting));

    (2)      利用task::then实现异步完成时所执行的操作

 

  createFileTadk.then([this](StorageFile^ storageFileSample) {  
         String^ filename=storageFileSample->Name;                              
        });   

       

task::then函数创建并返回的任务称为延续,异步工作成功完成后才会运行。若异步操作引发异常,或取消任务,则延续永远不会执行。以上是一个很简单的异步示例,在延续任务中没有异步任务,若在延续中我们还会再次执行异步任务,可能异步任务的延续中还会再有异步任务,这一系列的任务就会形成一个任务链,一环接一环,每个延续只有在前一个延续任务完成后才会执行,这就会形成这样一种形式:mytask.then().then().then();

如上例操作,我需要在创建文件后,还得往文件写入内容,写完文件我还得给用户一个提示:

 

    createFileTadk.then([this](StorageFile^ storageFileSample) ->IAsyncAction^ {       
    String^ userContent="abcdwfwe";
    create_task(FileIO::WriteTextAsync(storageFileSample, userContent)).then([this, storageFileSample, userContent]()
                {
        MessageDialog^ message=ref new MessageDialog("File is completed create!");
        message->ShowAsync();
                });    
    });

 

     捕获异步任务的异常

我们可以通过task::get获取任务结果,其可以获取已经传输到该任务的所有。

 createFileTadk.then([this](StorageFile^ storageFileSample) ->IAsyncAction^ {     
        String^ userContent="abcdwfwe";    
        return FileIO::WriteTextAsync(storageFileSample, userContent);
    }).then([](task<void> t){
        try
        {
            t.get();            
            OutputDebugString(L"the content has been write into file!");
            //tbText->Text="the content has been write into file";
        }
        catch(Platform::COMException^ e)
        {
            
        }
    });

 

posted on 2012-08-19 21:09  ShinyTang  阅读(3917)  评论(7编辑  收藏  举报

导航

作者:LucyTangLucyTang's Blog on 博客园
出处:http://www.cnblogs.com/jing870812/

本作品由LucyTang创作,采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。 任何转载必须保留完整文章,在显要地方显示署名以及原文链接。如您有任何疑问或者授权方面的协商,请给我留言