在我的ReceiveCallBack中是否有一個鎖定套接字的異步套接字?我在問,因爲另一個線程可能同時在套接字上發送數據。跨主題鎖定的套接字
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);
}
}
這個問題是基於你可以鎖定對象以使代碼線程安全的錯覺。你不能,你只能阻止代碼,阻止它同時使用共享對象。鎖語句僅使用一個對象來存儲狀態。這應該永遠不會是一個套接字。 – 2011-05-30 20:50:59