I have just started with parallel programming. I want to create an action delegate method that print a message on console. When I chenge Action<string> to Action<object> and PritMessage parameter to to object its work but with 'string compiler throws an error.
The best overloaded method match for 'System.Threading.Tasks.Task.Task(System.Action, object)'.
Argument 1: cannot convert from 'System.Action<string>' to 'System.Action<object>'
static void Main(string[] args)
{
string message = "test";
Action<string> print = PrintMessage;
Task task = new Task(print, message);
task.Start();
Console.ReadKey();
}
static void PrintMessage(string message)
{
Console.WriteLine(message);
}
If you examine the Task constructors, you'll see that you can't create a task with Action which accepts something other than no parameters or single object parameter.
For this particular sample you can simply run the Task with lambda, like this:
Task.Run(() =>
{
PrintMessage(message);
}
However, better approach is to change signature and cast an in-parameter:
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);
}
Or simply print the object in Console:
static void PrintMessage(object message)
{
Console.WriteLine(message);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With