I’m writing some code where the UI thread need to communicate with the background thread doing network communication. The code works, but would it be considered thread safe?
I would feel a lot better if someone experienced could lead me on to the right path on this…
static Mutex^ mut_currentPage = gcnew Mutex; static array<unsigned char>^ m_currentPage; property array<unsigned char>^ Write { void set(array<unsigned char>^ value) { mut_currentPage->WaitOne(); m_currentPage = value; mut_currentPage->ReleaseMutex(); } }
This is .NET C++ code… 🙂
It looks thread-safe, but you might want to think about exception handling; setting a field shouldn’t error (except perhaps
ThreadAbortException), but if the code was more complex, you’d want to ensure you release the mutex upon exception.I’d also look at
Monitor(‘lock’ in C#)One other thought: even if you lock the field access, an array is inherently mutable. Consider using
stringinstead, since this is immutable?