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; 
                }
            }
  • 相关阅读:
    HDU6301 SET集合的应用 贪心
    线段树与树状数组的对比应用
    树状数组
    JDBC链接MySQL数据库
    HDU4686Arc of Dream 矩阵快速幂
    HDU1757矩阵快速幂
    B1013. 数素数 (20)
    B1023. 组个最小数 (20)
    [教材]B1020. 月饼 (25)
    [教材]A1025. PAT Ranking (25)
  • 原文地址:https://www.cnblogs.com/qianblue/p/3365404.html
Copyright © 2011-2022 走看看