I have an array of MemoryStreams. The main thread is updating one element at a time and the other threads are iterating over the array and checking if they are free to read the elements. If a MemoryStream is locked in the array, they won't read it and continue to another MemoryStream in the array.

How can I implement this scenario I'm using the array as a buffer, the threads are reading from it and sending data over network, that's why I can't allow the main thread do the work of reading and sending the data. I need to make the other threads recognize and not read the element that is being updated.

Thank you

Re: Visual C# Language Array as a buffer in multithreading


You can use an array of mutexes. So mutex with index 0 would correspond to the MemoryStream in index 0. So when you want to access memory stream with index i you will have to call on the mutex with index i, try to acquire access to that mutex, and if you can't then just continue on. Then once you've acquired the mutex you can access the corresponding memroy stream and when you are finished with the memory stream you just have to release the mutex.

Re: Visual C# Language Array as a buffer in multithreading



From your description, it seems that there is only one MemoryStream element in being updated state at a specific time. thus, in my opinion, you just need a state recorder which record the position of being updated MemoryState.