C#中,Task Action错误

C#中,Task Action错误

代码这一部分,Task task1 = new Task(action,null);
提示报错原因是: 参数 1: 无法从“System.Action”转换为“System.Action”

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的重载没有int这种泛型,只有Action,你传递Action当然没法转换成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; } }

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632