天马行空  
I ---- Inject 投入 L ---- Loyal 忠诚 O ---- Observant 用心 V ---- Valiant 勇敢 E ---- Enjoyment 喜悦 Y ---- Yes 愿意 O ---- Obligation 责任

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 其中的代码可在 https://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; 
            }
        }

 

posted on 2013-10-12 15:52  浅蓝  阅读(319)  评论(0编辑  收藏  举报