码迷,mamicode.com
首页 > Windows程序 > 详细

C# async await 异步例子

时间:2019-08-22 11:10:33      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:ret   ttext   返回值   new   patch   wait   extc   text   btn   

 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 异步例子

标签:ret   ttext   返回值   new   patch   wait   extc   text   btn   

原文地址:https://www.cnblogs.com/zdc-shine/p/11392845.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!