using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ConsoleApp中task的状态
{
class Program
{
private static void Method(int i)
{
i =i *1000;
Thread.Sleep(i);
}
static void Main(string[] args)
{
Action<int> action = new Action<int>(Method);
Task task1 = new Task(action,null);
task1.Start();
}
}
}
代码这一部分,Task task1 = new Task(action,null);
提示报错原因是: 参数 1: 无法从“System.Action<int>”转换为“System.Action”
task的重载没有int这种泛型,只有Action<object>,你传递Action<int>当然没法转换成action,改成下面就行了
private static void Method(object state)
{
var o = (Data)state;
int a = o.x;
int b = o.y;
int i = a * b;
Console.WriteLine($"{a}和{b}相乘的结果是{i}");
}
static void Main(string[] args)
{
Action<object> action = new Action<object>(Method);
Task task1 = new Task(action, new Data { x=1,y=2});
task1.Start();
Console.ReadKey();
}
public class Data { public int x { get; set; }public int y { get; set; } }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ConsoleApp中task的状态
{
class Program
{
private static void Method(int a,int b)
{
i =a*b;
Console.WriteLine($"{a}和{b}相乘的结果是{i}");
}
static void Main(string[] args)
{
Action<int,int> action = new Action<int,int>(Method);
Task task1 = new Task(action,null);
task1.Start();
Console.ReadKey();
}
}
}