【发布时间】:2011-05-30 19:29:59
【问题描述】:
在我的异步套接字的 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);
}
}
【问题讨论】:
-
这个问题是基于您可以锁定对象以使代码线程安全的错觉。你不能,你只能阻止代码,阻止它同时使用共享对象。 lock 语句仅使用一个对象来存储状态。那应该永远是一个套接字。
标签: c# .net multithreading sockets parallel-processing