Imagine I have this code where inside Windows forms timer I can spawn some threads - but I ensure that ONLY one thread is running using following approach (as indicated by one of the answers from here - by Matt Johnson):
nb: let's assume for now this _executing
approach works and I don't use backgroundworker
, etc.
private volatile bool _executing;
private void TimerElapsed(object state)
{
if (_executing)
return;
_executing = true;
if(smth)
{
Thread myThread = new Thread(MainThread1);
myThread.IsBackground = true;
myThread.Start();
}else
{
Thread myThread = new Thread(MainThread2);
myThread.IsBackground = true;
myThread.Start();
}
}
public void MainThread1()
{
try
{
methodWhichAddelementTomyList(); // e.g., inside list.add();
}
finally
{_executing = false;}
}
public void MainThread2()
{
try
{
methodWhichAddelementTomyList(); // e.g., inside list.add();
}
finally
{_executing = false;}
}
Now I also have List
instance variable, which you can see I access from MainThread1
and MainThread2
- but since my logic above I ensure that MainThread1
and MainThread2
never run in parallel, do I still have to make the list
volatile
? Can I encounter issues
related to caching the list variable?
EDIT: And also does this approach protect me from running those threads in parallel? (The answer in the linked question is a bit different -it runs the work inside timer - so I want to double check).
EDIT2: Honestly there is no common opinion below whether I should apply volatile
keyword on my list
object or not. This state of affairs confuses me. So documented answer is still welcome; otherwise this is not fully answered