I am using a array m_aoAlternatingJobs in various functions of a class. These functions are accessed by different threads. Therefore I am using a Monitor-lock (c++cli) in each function that accesses this array prior to the actual access.
The problem now is, that in one function I am resizing the array. As described by the MSDN documentation, this will create a new array and copy values, so even if I did not use the Monitor (I am doing on each necessary place), I would not get a program crash in any case, but other threads could access the old array (see also here: stackoverflow: Is Array.Resize(..) threadsafe?).
If I am using a Monitor directly on the array object, the Monitor fails to exit with SynchronizationLockException because the Exit is called on the new, unlocked object. But I do have to use a lock to avoid resizing the array while in use on another function. Thus I'm doing the following trick to avoid access to the array while being resized:
void Class1::JobsCount::set (int i_iJobCount)
{
if (i_iJobCount < 1) i_iJobCount = 1;
bool bSuccess = false;
Object^ oRefOld;
try
{
bSuccess = Monitor::TryEnter (m_aoJobs, msc_iMonitorTimeout);
if (!bSuccess) return;
oRefOld = m_aoAlternatingJobs;
Array::Resize (m_aoJobs, i_iJobCount);
}
finally
{ if (bSuccess) Monitor::Exit (oRefOld); }
}
I'm not getting an Exception any more, but the more important question is: Will this effectively block access to the array while the resize is being done?
Edit:
I am aware of the possibility of using a separate lock object, thanks for the advices. Nevertheless I would like to receive an answer about the question above.