I need to know how I can have a small block of adjacent lines of code run sequentially without any other thread being able to have CPU time.
if (status != Status.Pending)
return;
status = Status.Locked;
Background
I'm developing an application with a user interface on a main thread that fills a list of outstanding asynchronous tasks that an army of helper-threads chip away at. I began development on custom objects to represent these activities before realizing that tasks were built-in. For this project, I'd like to continue with my custom task-like objects.
I have threads wait around for tasks to appear in the list, then the first one to lock it gets to keep it. The very first line of each tasks used to set its status to Locked - but even in the tiny gap between finding the task and locking the task multiple threads occasionally take the same task.
Priorities, Priorities
My first idea was to look into how Priorities of threads are handled. This documentation seems to describe what I was hoping - where a high priority thread takes all the resources before any lower priority threads. That seemed like a good idea that if my body of work code was preceeded by raising the current thread's priority temporarily.
Thread.CurrentThread.Priority = ThreadPriority.Highest;
But from the same site this code example shows that over a period of time the tasks all receive enough attention that I couldn't rely on one high priority thread completing its body of work. I expect that multi-cores in the CPU is the culprit.
// The example displays output like the following:
// ThreadOne with Normal priority has a count = 755,897,581
// ThreadThree with AboveNormal priority has a count = 778,099,094
// ThreadTwo with BelowNormal priority has a count = 7,840,984
Oh and here is the nail in the coffin to that idea delivered by our glorious leader Jeff Atwood.
Freeze!
My next idea has been to freeze every other helper-thread temporarily, then thaw them after my block is complete. Urk! In a multi-core CPU environment I can imagine this code potentially running on two cores at the same time; and that would be game over.
foreach (Thread thread in ActivityQueue.threads)
if (thread != Thread.CurrentThread)
thread.Suspend();
What else?
What other options do I have for making sure that I can check if something is locked, then lock it or back out when code could be running simultaneously? Examples using the built in Task object are welcome.
This question was marked as a duplicate. I say that the fundamental answer from @Daniel Hilgarth of No, you can't points me away from that direction. As pointed out in the comments, I've boo-boo'd with a typical XY question - but that is easy for me to identify only in hind-sight.