I have created a console app which print the number in a for loop using C# Task.Run()
method. If you look at the code, I am initializing the Employee object
in the loop and pass the number in the method, though it prints the same number.
Code:
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 500; i++)
{
Task.Run(() => new Employee().ProcessEmployee(i));
}
Console.Read();
}
}
public class Employee
{
public void ProcessEmployee(int employeeId)
{
Console.WriteLine($"The number is: {employeeId} and thread is {Thread.CurrentThread.ManagedThreadId}");
}
}
Output:
The question is- How would I fix this issue? I still want to use Task.Run()
method because in my real application scenarios, I want to process the stream (JSON data) in a different thread and do not want to block my main callback method which receive the stream (JSON data).
Thanks in advance.