日期:2014-05-18  浏览次数:20795 次

异步写数据
我的 往流中写数据 代码如下: 求大神帮我看看我的思路是否正确?? (异步)
自己测试了下,是有问题的,一直在发送最后一次的消息。(原意想 有消息发,无消息等待)
要不要定义一个事件

_SendThread = new Thread(new ThreadStart(SendProcess));
...

private void SendProcess()
{
  lock(networkStream)
  {
  //创建异步写入委托
  networkStream.BeginWrite(sendBuf,0,sendBuf.length,new AsyncCallback (WriteData),networkStream);
  }
}

private void WriteData( IAsyncResult iAsyncResult )
{
  IAsyncResult ar = (IAsyncResult)iAsyncResult;

  String msg = null;
  lock (_sendPool.SyncRoot)
  {
  if (_sendPool.Count() > 0)
  msg = _sendPool.Dequeue();
  else
  Thread.Sleep(1000); //这一句 不妥..
  }
  if (msg != null)
  {
  _sendBuf = Encoding.ASCII.GetBytes(msg);
  networkStream.EndWrite(ar); //这一句 位置是否正确??
  }
   
  lock(networkStream) //调用自身,完成无限循环
  {
  networkStream.BeginWrite(_sendBuf, 0, _sendBuf.Length, new AsyncCallback(WriteData), networkStream);
  }
}



------解决方案--------------------
你这样写怪怪的~

用一个线程检查队列,如果>0,在调用BeginWrite

不要在callback里面去sleep,去判断,放到SendProcess里面