I am using the code below for creating multiple tasks in C#:
private static List<Task> _taskList = new List<Task>();
private static ConcurrentQueue<string> cred = new ConcurrentQueue<string>();
private static void TaskMethod1(string usercred)
{
// I am doing a bunch of operations here, all of them can be replaced with
// a sleep for 25 minutes.
// After all operations are done, enqueue again.
cred.Enqueue("usercred")
}
private static void TaskMethod()
{
while(runningService)
{
string usercred;
// This will create more than one task in parallel to run,
// and each task can take up to 30 minutes to finish.
while(cred.TryDequeue(out usercred))
{
_taskList.Add(Task.Run(() => TaskMethod1(usercred)));
}
}
}
internal static void Start()
{
runningService = true;
cred.enqueue("user1");
cred.enqueue("user2");
cred.enqueue("user3");
Task1 = Task.Run(() => TaskMethod());
}
I am encountering a strange behaviour in the code above. By putting a breakpoint at line _taskList.Add(Task.Run(() => TaskMethod1(usercred)));
, I am checking value of usercred
every time TaskMethod1
is called and it is not null while being called but in one of the cases the value of usercred
is null
inside TaskMethod1
. I have no clue how this could be happening.