C# async await 异步例子

Posted zdc-shine

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# async await 异步例子相关的知识,希望对你有一定的参考价值。

 public const string  Linefeed= "\r\n";
        private void BtnasyncAwait_Click(object sender, RoutedEventArgs e)
       
            SetTextShow("111 balabala. My Thread ID is :" + Thread.CurrentThread.ManagedThreadId);
             AsyncMethod();
            SetTextShow("222 balabala. My Thread ID is :" + Thread.CurrentThread.ManagedThreadId);

       
 
        private void SetTextShow(string textContent)
       
            txtInfo.Dispatcher.Invoke(new Action(()=> txtInfo.Text += DateTime.Now.ToString() + " " + textContent + Linefeed; ));
           
       
        private void ClearTextShow()
       
            txtInfo.Dispatcher.Invoke(new Action(() => txtInfo.Text = string.Empty; ));
          
       
  private async Task AsyncMethod()
       
            var ResultFromTimeConsumingMethod = TimeConsumingMethod();
            string Result = await ResultFromTimeConsumingMethod + " + AsyncMethod. My Thread ID is :" + Thread.CurrentThread.ManagedThreadId;
            SetTextShow(Result);
            //返回值是Task的函数可以不用return
       
 
        //这个函数就是一个耗时函数,可能是IO操作,也可能是cpu密集型工作。
        private Task<string> TimeConsumingMethod()
       
            var task = Task.Run(() =>
                SetTextShow("Helo I am TimeConsumingMethod. My Thread ID is :" + Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(5000);
                SetTextShow("Helo I am TimeConsumingMethod after Sleep(5000). My Thread ID is :" + Thread.CurrentThread.ManagedThreadId);
                return "Hello I am TimeConsumingMethod";
            );
            return task;
       

以上是关于C# async await 异步例子的主要内容,如果未能解决你的问题,请参考以下文章

说说C#的async和await 解决卡顿问题 转

抓住异步编程async/await语法糖的牛鼻子

[译] C# 5.0 中的 Async 和 Await (整理中...)

同步和异步 setTimeou(异步) async和await promise(疑惑点)

同步和异步 setTimeou(异步) async和await promise(疑惑点)

体验异步的终极解决方案-ES7的Async/Await