zoukankan      html  css  js  c++  java
  • async 和 await

    win8 app开发中使用async,await可以更方便地进行异步开发。

    async,await的使用可参考代码:Async Sample: Example from "Asynchronous Programming with Async and Await" (http://code.msdn.microsoft.com/Async-Sample-Example-from-9b9f505c);

    async 标记的函数中标明  await 的地方就是异步开始的地方,后面的代码其实就是回调函数中执行了。

    也可以用Task执行新的线程。可参考:await 返回 Task 的 async 方法

     http://wenku.baidu.com/view/d011c98f680203d8ce2f24f9.html 其中的代码可在 http://files.cnblogs.com/qianblue/async_await.zip 下载。

    await 的作用就是标记 后面的代码在新线程中执行。

    经验1:

    在下面的VM代码中,使用FileIO.ReadTextAsync(sf) 时,如果跳过DoReadFileAsync这个中间函数调用,采用string fContent = ReadFileAsync().GetAwaiter().GetResult();,那么经常会卡住,应该是线程的关系。

            /// <summary>
            /// The <see cref="CurrentFile" /> property's name.
            /// </summary>
            public const string CurrentFilePropertyName = "CurrentFile";
    
            private string _currentFile = null;
    
            /// <summary>
            /// Sets and gets the CurrentFile property.
            /// Changes to that property's value raise the PropertyChanged event. 
            /// </summary>
            public string CurrentFile
            {
                get
                {
                    return _currentFile;
                }
    
                set
                {
                    if (_currentFile == value)
                    {
                        return;
                    }
    
                    RaisePropertyChanging(CurrentFilePropertyName);
                    _currentFile = value;
                    RaisePropertyChanged(CurrentFilePropertyName);
    
                    DoReadFileAsync(_currentFile);
                }
            }
    
            private async Task DoReadFileAsync(string fName)
            {
    
                //string fContent =  FileIO.ReadTextAsync(_currentFile).GetResults();
    
                string f = await ReadFileAsync(fName);
                //string fContent = ReadFileAsync().GetAwaiter().GetResult();
                await _dialogService.ShowMessageBox(f, "fContent");
            }
    
            private async Task<string> ReadFileAsync(string fName)
            {
                try
                {
                    IStorageFile sf = await ApplicationData.Current.LocalFolder.GetFileAsync(fName);
                    var fileContent = await FileIO.ReadTextAsync(sf);
    
                    return fileContent;
                }
                catch(Exception exc)
                {
                    return null; 
                }
            }
  • 相关阅读:
    tkinter 表格
    Python编程学习笔记 随时更新
    WIN32窗口程序
    OutputDebugString方便格式化WIN32封装
    免费的剪贴板工具Ditto安装与使用
    Notepad++安装json插件
    华为机试训练题
    Python+Flask+MysqL的web建设技术过程
    python Django 用法总结(转)
    python Robot Framework用法总结(转)
  • 原文地址:https://www.cnblogs.com/qianblue/p/3365404.html
Copyright © 2011-2022 走看看