Trying to understand how the thread context switch affects the execution of iterations of the Parallel class through ForEach or For usage. I tried to increase CPU usage up to 100% with execution of several processes, but not a single Parallel's iteration has changed it's Thread.CurrentThread.ManagedThreadId value.
To increase CPU up to 100% usage, I've started several high priority processes, including the example.
Code where do we need to handle thread context switch:
Parallel.For(0, 3, (index, i) => { var firstId = Thread.CurrentThread.ManagedThreadId; while (true) { var rnd = new Random(index); checkIds(firstId, Thread.CurrentThread.ManagedThreadId); var digits = new List<int>(); for (int j = 0; j < 10000; j++) { digits.Add(rnd.Next()); if (continueWriteLine) Console.WriteLine($"ID: = {Thread.CurrentThread.ManagedThreadId}"); } if (continueWriteLine) digits.ForEach(Console.WriteLine); } });Code that tries to handle thread switch:
if (firstId != currentId) { continueWriteLine = false; Thread.Sleep(1000); Console.WriteLine($"{firstId} - {currentId}"); }
So, I have several questions:
Can a thread switch to another one, during the execution of an iteration of the Parallel class, by some reason e.g.
Thread.Sleep,lockstatement,Mutex, etc.?And how this threads' switch affects the
ManagedThreadIdproperty, if they really will be switched?Will it be safe to use
ManagedThreadIdas unique key of theConcurrentDictionaryfrom which any information can be retrieved for a current operation e.g. information about file's reading: current line, desired object to read, already read objects, and a lot of other things that are needed during current operation?
P.S. The reason for the solution given in the third question is lack of desire to transfer most of this data between methods that helps me read and process every new line of file in order to maintain context of file's processing. Maybe the solution would be to transfer only one object between parser's methods, something like FileProcessingInfo, that contains all context data (which I mentioned in the third question), but I don't know for sure which solution would be better.