At first I assume I do need writerlock here but Im not sure (not much experience with that) what if I dont use it.
On the server side, there are client classes for each connected client. Each class contains public list which every other class can write to. Client requests are processed via threadpool workitems.
class client
{
public List <string> A;
someEventRaisedMethod(param)
{
client OtherClient=GetClientByID(param) //selects client class by ID sent by msg sender
OtherCLient.A.Add("blah");
}
}
What if two instances reference the same client and both try OtherCLient.A.Add(“blah”)? Isnt be here some writer lock? It works for me but I encounter some strange issues that I think are due to this.
Thank you!
(update: as always, Eric Lippert has a timely blog entry)
If you don’t use a lock, you risk either missing data, state corruption, and probably the odd
Exception– but only very occasionally, so very hard to debug.Absolutely you need to synchronize here. I would expose a lock on the client (so we can span multiple operations):
You could make a synchronous
Addmethod onotherClient, but it is often useful to span multiple – perhaps to checkContainsand thenAddonly if missing, etc.Just to clarify 2 points:
lock; otherwise it doesn’t workLockObjectshould be a readonly reference-typefor the second, perhaps: