Is it a good idea in my ReceiveCallBack of an asynchronous socket to Lock() the socket there? I’m asking because it’s possible that another thread is sending data on the socket at the same time.
private void ReceiveCallback(IAsyncResult ar)
{
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
lock(client)
{
int bytesRead = client.EndReceive(ar);
// do some work
// Kick off socket to receive async again.
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
}
// This is commonly called by another thread
public void SendMessage(string cmdName, Object data)
{
lock (client)
{
client.Send(arrayofdata, 0, arraylength, 0);
}
}
If you want to make it thread-safe and be able to send and receive simultaneously you need to create two lock sync objects:
It is generally a good practice to have dedicated
syncRootobjects instead of locking on other classes or members. This allows to avoid subtle deadlocks.