C# Task.Run()运行“含参数和返回值的方法”的用法

发布时间 2023-03-30 11:57:04作者: wangxiangtan

测试环境:Win10 64位+VS2015 update3;

一、无参数无返回值情况

 1 private void button9_Click(object sender, EventArgs e)
 2 {
 3     //Task.Run(Method0);//报错,在Run(Action)和Run(Func<Task>)之间有二义性;
 4     //Task.Run(() => Method0);//× 
 5     Task.Run(() => { Method0(); });
 6     Task.Run(new Action(Method0));
 7 }
 8 
 9 //无参数,无返回值;
10 private void Method0()
11 {
12     Console.WriteLine($"thread ID: {Thread.CurrentThread.ManagedThreadId},Hello world.");
13 }

 

二、有参数无返回值情况

 1         private void Method1(string str)
 2         {
 3             Console.WriteLine($"thread ID: {Thread.CurrentThread.ManagedThreadId}, {str}");
 4         }
 5         private void Method1(string str, int times)
 6         {
 7             string strTemp = $"thread ID: {Thread.CurrentThread.ManagedThreadId},";
 8             for (int i = 0; i < times; i++)
 9             {
10                 strTemp += str;
11             }
12             Console.WriteLine(strTemp);
13         }
14         //调用;
15         private void button9_Click(object sender, EventArgs e)
16         {            
17             string str = "Elden ring";
18             int times = 3;
19             Task.Run(() => { Method1("0 " + str); });
20             BeginInvoke(new Action<string>(Method1), "1 " + str);
21             BeginInvoke(new Action<string>(Method1), new object[] { "2 " + str });
22 
23             Task.Run(() => { Method1("3 " + str, times); });25             BeginInvoke(new Action<string, int>(Method1), "4 " + str, times);
26             BeginInvoke(new Action<string, int>(Method1), new object[] { "5 " + str, times }); 
27         }

 

三、有参数有返回值情况

 

 1         private string Method2(string str)
 2         {
 3             Console.WriteLine($"thread ID: {Thread.CurrentThread.ManagedThreadId}");
 4             return "Hello " + str;
 5         }
 6         private void button9_Click(object sender, EventArgs e)
 7         {
 8             
 9             string elden = "Elden Ring";
10             //Task<string> t = Task.Run<string>(() => { Method2(elden); });
11             Task<string> t = Task.Run<string>(() => { return Method2("1 "+elden); });
12             Task<string> t3 = Task.Run(() => { return Method2("2 " + elden); });
13             Console.WriteLine(t.Result);
14             Console.WriteLine(t3.Result);
15             string temp = string.Empty;
16 
17             Func<string, string> f = new Func<string, string>(Method2);
18             string oo = "haha";
19             IAsyncResult result = f.BeginInvoke("3 " + elden, new AsyncCallback((a)=>
20             {
21                 temp = f.EndInvoke(a) + a.AsyncState.ToString();
22                 Console.WriteLine(temp);
23             }), oo); 
24         }