My situation is this:
- I only have access to a part of the code that is already running in multithreading, so I'm not creating the threads and can not access the part of the code where the threads are being created
- I need to ensure that a fairly complex (multiple functions are called, there is DB access involved, etc.) portion of code is executed exclusively by a single thread at a time
So my question is, it is possible to do that? and if that so, what is the best way to do it?
Here is some illustrative code of what I'm trying to acomplish:
// This method is executed by multiple threads at the same time
protected override void OnProcessItem()
{
MyObject myObject = new MyObject();
// Begin of the code that should be executed only once at a time
// by each thread
bool result = myObject.DoComplexStuff();
if(result == true)
{
this.Logger.LogEvent("Write something to log");
// ... Do more stuff
}
else
{
this.Logger.LogEvent("Write something else to log");
// ... Do more stuff
}
// ... Do more stuff
// End of the code that should be executed only once at a time
// by each thread
}
Some background
Before asking here I did an small investigation effort and end reading this:
https://learn.microsoft.com/en-us/dotnet/standard/threading/overview-of-synchronization-primitives
But still I'm not sure what's the best approach or how to implement it in mi scenario.
Additionally I'm no expert at multithreading as you may guess.