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

Posted 望乡潭

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# Task.Run()运行“含参数和返回值的方法”的用法相关的知识,希望对你有一定的参考价值。

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

一、无参数无返回值情况

 private void button9_Click(object sender, EventArgs e)
 
     //Task.Run(Method0);//报错,在Run(Action)和Run(Func<Task>)之间有二义性;
     //Task.Run(() => Method0);//× 
     Task.Run(() =>  Method0(); );
     Task.Run(new Action(Method0));
 
 
 //无参数,无返回值;
 private void Method0()
 
     Console.WriteLine($"thread ID: Thread.CurrentThread.ManagedThreadId,Hello world.");
 

 

二、有参数无返回值情况

         private void Method1(string str)
         
             Console.WriteLine($"thread ID: Thread.CurrentThread.ManagedThreadId, str");
         
         private void Method1(string str, int times)
         
             string strTemp = $"thread ID: Thread.CurrentThread.ManagedThreadId,";
             for (int i = 0; i < times; i++)
             
                 strTemp += str;
             
             Console.WriteLine(strTemp);
         
         //调用;
         private void button9_Click(object sender, EventArgs e)
                     
             string str = "Elden ring";
             int times = 3;
             Task.Run(() =>  Method1("0 " + str); );
             BeginInvoke(new Action<string>(Method1), "1 " + str);
             BeginInvoke(new Action<string>(Method1), new object[]  "2 " + str );
 
             Task.Run(() =>  Method1("3 " + str, times); );             BeginInvoke(new Action<string, int>(Method1), "4 " + str, times);
             BeginInvoke(new Action<string, int>(Method1), new object[]  "5 " + str, times ); 
         

 

三、有参数有返回值情况

 

         private string Method2(string str)
         
             Console.WriteLine($"thread ID: Thread.CurrentThread.ManagedThreadId");
             return "Hello " + str;
         
         private void button9_Click(object sender, EventArgs e)
         
             
             string elden = "Elden Ring";
             //Task<string> t = Task.Run<string>(() =>  Method2(elden); );
             Task<string> t = Task.Run<string>(() =>  return Method2("1 "+elden); );
             Task<string> t3 = Task.Run(() =>  return Method2("2 " + elden); );
             Console.WriteLine(t.Result);
             Console.WriteLine(t3.Result);
             string temp = string.Empty;
 
             Func<string, string> f = new Func<string, string>(Method2);
             string oo = "haha";
             IAsyncResult result = f.BeginInvoke("3 " + elden, new AsyncCallback((a)=>
             
                 temp = f.EndInvoke(a) + a.AsyncState.ToString();
                 Console.WriteLine(temp);
             ), oo); 
         

 

以上是关于C# Task.Run()运行“含参数和返回值的方法”的用法的主要内容,如果未能解决你的问题,请参考以下文章

C# 理解阻塞 UI 和异步/等待与 Task.Run 的问题?

C# Task.Run() 与 C++ std::async()

避免 Task.Run 导致主线程死锁(C#)

C#使用异步操作时的注意要点(翻译)

Task.Run 和Task.Factory.StartNew 区别

C#中利用Attribute实现AOP