3

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);
}

1 Answer 1

3

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);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.