Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closures and Tasks

Is there any functional difference between these to function calls.

Method1:

public static void PrintMe(object obj)
{
    Task task = new Task(() =>
    {
        Console.WriteLine(obj.ToString());
    });
    task.Start();
}

Method2:

public static void PrintMe(object obj)
{
    Task task = new Task((object arg) =>
    {
        Console.WriteLine(arg.ToString());
    }, obj);
    task.Start();
}
like image 846
Verax Avatar asked Feb 22 '12 09:02

Verax


1 Answers

The first one passes the variable obj to the task. The second one passes the value of obj.

To see the difference assign something else to obj after creating the task.

public static void PrintMe(object obj)
{
    Task task = new Task(() =>
    {
        Console.WriteLine(obj.ToString());
    });
    obj = "Surprise";        
    task.Start();
}
like image 114
adrianm Avatar answered Oct 03 '22 05:10

adrianm