Possible Duplicate:
Are C# arrays thread safe?
I have been programming C# for 10 months now. I am now learning multi-threading and seems to be working nicely. I have multi-dimension array like
string[,] test = new string[5, 13];
I have the threads calling methods that end up saving their outputs to different coordinates inside the array above. without any one thread writing to the same location as another thread.
So thread1 might write to test[1,10] but no other thread will ever write to test[1,10]
My question is: I have read about using locks on objects like my array, do I have to worry at all about locks even though my threads might access to the test array at the same time but never write to the same coordinates(memory location)?
So far in my testing I have not had any issues, but if someone more seasoned than myself knows I could have issue then I’ll look into use locks.
If you can ensure that no two threads will ever attempt to read or write to the same element then you have no need to do any locking, and if you do add locking you will slow down your code.
You should however take the time to add comments as appropriate to explain that, (and possibly why) no threads ever access the same elements to avoid future problems that Jim Fell has mentioned in his answer.
Update: Many of the other posters are continuing to suggest that locking be used merely as a safeguard against mistakes by future developers. To that end, it really depends on your application. If performance really isn’t much of an issue, then sure, go ahead and synchronize access to the elements.
However, most of the time in which multiple threads are accessing a single array the reason that multiple threads exist is to perform parallel processing on large amounts of data in which performance is a significant concern. If it wasn’t much of a concern, then you could just use a single thread and be far more at ease about it not being messed up by others. In such high performance computing reliance on lock (in various forms) is, as a rule, minimized whenever possible. Synchronization through separation of data (meaning preventing them from ever reading/writing to the same memory locations) is far superior to using locks, when it is feasible.