C# 操作委托接受字符串参数的任务
我刚刚开始并行编程。我想创建一个在控制台上打印消息的操作委托方法。当我将C# 操作委托接受字符串参数的任务,c#,task-parallel-library,delegates,C#,Task Parallel Library,Delegates,我刚刚开始并行编程。我想创建一个在控制台上打印消息的操作委托方法。当我将Action设置为Action并将PritMessage参数设置为对象其工作,但使用“string编译器会抛出错误 匹配的最佳重载方法 'System.Threading.Tasks.Task.Task(System.Action,object)'。 参数1:无法从“System.Action”转换为 “系统。行动” static void Main(字符串[]args) { string message=“test”; 动
Action
设置为Action
并将PritMessage
参数设置为对象其工作,但使用“string
编译器会抛出错误
匹配的最佳重载方法
'System.Threading.Tasks.Task.Task(System.Action,object)'。参数1:无法从“System.Action”转换为 “系统。行动”
static void Main(字符串[]args)
{
string message=“test”;
动作打印=打印消息;
任务任务=新任务(打印、消息);
task.Start();
Console.ReadKey();
}
静态无效打印消息(字符串消息)
{
控制台写入线(消息);
}
如果检查,您将看到无法创建具有操作的任务,该操作只接受无参数或单个对象
参数以外的内容
对于此特定示例,只需使用lambda运行任务
,如下所示:
Task.Run(() =>
{
PrintMessage(message);
}
但是,更好的方法是更改签名并强制转换in参数:
static void Main(string[] args)
{
var message = "test";
Task task = new Task(PrintMessage, message);
task.Start();
Console.ReadKey();
}
static void PrintMessage(object messageObj)
{
var message = messageObj as string;
Console.WriteLine(message);
}
或者只需在控制台中打印对象:
static void PrintMessage(object message)
{
Console.WriteLine(message);
}
static void PrintMessage(object message)
{
Console.WriteLine(message);
}