(All of the below are simplified for brevity)
I have a static reference to a processing object.
The Processor contains a function to which I can pass an object Package, which is the info to be processed.
The Package comes from a list of lots of packages which should be processed. These packages are unqique; there are not multiple references to the same object here.
I start many threads so that I can process the packages in toProcess in parallell. The threads Pop() an available Package from the toProcess stack until the stack is empty.
My question is now: Can I risk that package in Check is overwritten by another thread, or will the other thread “create a copy” of Check?
static class Program
{
static Processor processor = new Processor();
static Stack<Package> toProcess;
static Object sync = new Object();
static void RunThreads()
{
toProcess = GetPackages();
//start many threads using the Work delegate
}
static void Work()
{
while(true)
{
Package p;
lock(sync)
{
if(toProcess.Count == 0)
break;
p = toProcess.Pop();
}
processor.Check(p);
}
}
}
class Processor
{
public void Check(Package package)
{
//do many analyses on p and report results of p's analysis to elsewhere
}
}
class Package
{
//properties
}
It’s not really clear what you mean, but each independent call to
Checkwill have its ownpackagevariable. That variable is local to not just that thread, but that invocation ofCheck(so recursive calls won’t change it either).Now if you pass the same
Packagereference toCheckin multiple different threads, then yes, they will all be processing the same object, which may cause problems. But thepackagevariables themselves will be independent in the different calls.