using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ConsoleApplication1 { public delegate int GetSum(object index); class Program { static void Main(string[] args) { /* Task task = new Task(new Action(Test)); task.Start(); Console.Read(); */ //最初的正确方法 //Task<int> task = new Task<int>(n=>Sum((Int32)n), 100); //正确的定义方法一 Task<int> task = new Task<int>(new Func<object,int>(Sum),10); //错误的定义方法二 //Task<int> task1 = new Task<int>(new Func<in object,out int>(Sum), 20); //方法三错误 GetSum getSum = new GetSum(Sum); Task<int> task1 = new Task<int>((Func<object, int>)getSum, 20); Console.WriteLine("Current Status:"+task.Status); task.Start(); Console.WriteLine("Current Status:" + task.Status); Console.WriteLine(task.Result); Thread.Sleep(60); Console.WriteLine("Current Status:" + task.Status); Console.Read(); } private static void Test() { Console.WriteLine("Hello,World!"); } //正确的方法一 private static int Sum(object input) { int result = 0; for (int i = 0; i < (int)input;i++ ) { checked { result += i; } //result=checked(result+i); } return result; } //正确的方法二 private static int SumSecond(int input) { int result = 0; for (int i = 0; i < (int)input; i++) { checked { result += i; } //result=checked(result+i); } return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ConsoleApplication1 { public delegate int GetSum(object index); class Program { static void Main(string[] args) { /* Task task = new Task(new Action(Test)); task.Start(); Console.Read(); */ //最初的正确方法 //Task<int> task = new Task<int>(n=>Sum((Int32)n), 100); //注意这里的(Int32)强制转换 //正确的定义方法一 Task<int> task = new Task<int>(new Func<object,int>(Sum),10); //错误的定义方法二 //Task<int> task1 = new Task<int>(new Func<in object,out int>(Sum), 20); //方法三错误 //GetSum getSum = new GetSum(Sum); //Task<int> task1 = new Task<int>((Func<object, int>)getSum, 20); //方法四 Task<int> taskForth = new Task<int>(delegate(object input) { return 100; }, 30); Console.WriteLine("Current Status:"+task.Status); task.Start(); Console.WriteLine("Current Status:" + task.Status); Console.WriteLine(task.Result); Thread.Sleep(60); Console.WriteLine("Current Status:" + task.Status); taskForth.Start(); Console.WriteLine(taskForth.Result); Console.Read(); } private static void Test() { Console.WriteLine("Hello,World!"); } //正确的方法一 private static int Sum(object input) { int result = 0; for (int i = 0; i < (int)input;i++ ) { checked { result += i; } //result=checked(result+i); } return result; } //正确的方法二 private static int SumSecond(int input) { int result = 0; for (int i = 0; i < (int)input; i++) { checked { result += i; } //result=checked(result+i); } return result; } } }