Closure and Tasks

Is there any functional difference between the two for calling functions.

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(); } 
+6
source share
1 answer

The first passes the obj task. The second 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(); } 
+9
source

Source: https://habr.com/ru/post/909063/


All Articles