欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

一个简单的例子看明白 async await Task

程序员文章站 2023-12-31 15:06:28
测试代码: 1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.L ......

测试代码:

  1 using system;
  2 using system.collections.generic;
  3 using system.componentmodel;
  4 using system.data;
  5 using system.drawing;
  6 using system.linq;
  7 using system.text;
  8 using system.threading;
  9 using system.threading.tasks;
 10 using system.windows.forms;
 11 using utils;
 12 
 13 namespace test
 14 {
 15     public partial class form1 : form
 16     {
 17         public form1()
 18         {
 19             initializecomponent();
 20         }
 21 
 22         private void form1_load(object sender, eventargs e)
 23         {
 24 
 25         }
 26 
 27         /// <summary>
 28         /// 执行任务
 29         /// </summary>
 30         public string dowork(string str)
 31         {
 32             thread.sleep(3000); //模拟延迟 比如网络请求 用了3000毫秒
 33             return "输出:" + str;
 34         }
 35 
 36         /// <summary>
 37         /// 执行任务
 38         /// </summary>
 39         public task<string> doworkbytask(string str)
 40         {
 41             return task.run(() =>
 42             {
 43                 thread.sleep(3000); //模拟延迟 比如网络请求 用了3000毫秒
 44                 return "输出:" + str;
 45             });
 46         }
 47 
 48         /// <summary>
 49         /// 测试1
 50         /// </summary>
 51         private async void button1_click(object sender, eventargs e)
 52         {
 53             logtimeutil logtime = new logtimeutil();
 54 
 55             var t1 = doworkbytask("测试值1");
 56 
 57             var t2 = doworkbytask("测试值2");
 58 
 59             string r1 = await t1;
 60 
 61             textbox1.appendtext(r1 + "\r\n");
 62 
 63             string r2 = await t2;
 64 
 65             textbox1.appendtext(r2 + "\r\n");
 66 
 67             logtime.logtime("耗时", textbox1);
 68         }
 69 
 70         /// <summary>
 71         /// 测试2 
 72         /// 
 73         /// 等效于 测试1
 74         /// </summary>
 75         private void button2_click(object sender, eventargs e)
 76         {
 77             task.run(() => //如果不加task.run,界面会卡
 78             {
 79                 logtimeutil logtime = new logtimeutil();
 80 
 81                 task<string> t1 = task.run<string>(() => { return dowork("测试值1"); });
 82                 task<string> t2 = task.run<string>(() => { return dowork("测试值2"); });
 83 
 84                 task.waitall(t1, t2);
 85 
 86                 this.invoke(new action(() => //线程中修改控件数据要使用invoke
 87                 {
 88                     textbox1.appendtext(t1.result + "\r\n");
 89                     textbox1.appendtext(t2.result + "\r\n");
 90                 }));
 91 
 92                 logtime.logtime("耗时", textbox1);
 93             });
 94         }
 95 
 96         /// <summary>
 97         /// 测试3 
 98         /// </summary>
 99         private async void button3_click(object sender, eventargs e)
100         {
101             logtimeutil logtime = new logtimeutil();
102 
103             var r1 = await doworkbytask("测试值1");
104 
105             textbox1.appendtext(r1 + "\r\n");
106 
107             var r2 = await doworkbytask("测试值2");
108 
109             textbox1.appendtext(r2 + "\r\n");
110 
111             logtime.logtime("耗时", textbox1);
112         }
113 
114         /// <summary>
115         /// 测试4
116         /// 
117         /// 等效于 测试3
118         /// </summary>
119         private void button4_click(object sender, eventargs e)
120         {
121             task.run(() => //如果不加task.run,界面会卡
122             {
123                 logtimeutil logtime = new logtimeutil();
124 
125                 task<string> t1 = task.run<string>(() => { return dowork("测试值1"); });
126                 t1.wait();
127                 this.invoke(new action(() => //线程中修改控件数据要使用invoke
128                 {
129                     textbox1.appendtext(t1.result + "\r\n");
130                 }));
131 
132                 task<string> t2 = task.run<string>(() => { return dowork("测试值2"); });
133                 t2.wait();
134                 this.invoke(new action(() => //线程中修改控件数据要使用invoke
135                 {
136                     textbox1.appendtext(t2.result + "\r\n");
137                 }));
138 
139                 logtime.logtime("耗时", textbox1);
140             });
141         }
142 
143     }
144 }

测试输出:

一个简单的例子看明白 async await Task

附 logtimeutil.cs:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;
using system.windows.forms;

namespace utils
{
    /// <summary>
    /// 记录耗时
    /// </summary>
    public class logtimeutil
    {
        private datetime _lasttime;

        public logtimeutil()
        {
            _lasttime = datetime.now;
        }

        /// <summary>
        /// 记录耗时
        /// </summary>
        public void logtime(string msg)
        {
            double d = datetime.now.subtract(_lasttime).totalseconds;
            logutil.log(msg + ",耗时:" + d.tostring("0.000") + " 秒");
        }

        /// <summary>
        /// 记录耗时
        /// </summary>
        public void logtime(string msg, textbox txt)
        {
            double d = datetime.now.subtract(_lasttime).totalseconds;
            msg = msg + ",耗时:" + d.tostring("0.000") + " 秒\r\n";
            if (txt.invokerequired)
            {
                txt.invoke(new action(() =>
                {
                    txt.appendtext(msg);
                }));
            }
            else
            {
                txt.appendtext(msg);
            }
        }
    }
}

 

上一篇:

下一篇: