• C# async await 异步例子


     public const string  Linefeed= " ";
            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;
            }
  • 相关阅读:
    ObjectARX代码片段二
    外部程序通过COM启动AutoCAD时RPC_E_CALL_REJECTED的问题解决办法
    ObjectARX代码片段一
    Sublime Text 3 修改插件安装位置【sublime text、插件路径、Data】
    Bug的处理
    界面测试的方法要点
    并发用户数、吞吐量、思考时间的计算公式
    常用测试工具下载
    SVN安装配置详解
    Loadrunner录制脚本时选择协议
  • 原文地址:https://www.cnblogs.com/zdc-shine/p/11392845.html
Copyright © 2020-2023  润新知