110,561
社区成员
发帖
与我相关
我的任务
分享
private void RecvData()
{
while(bReceiving)
{
lock (this)
{
IAsyncResult iar = recvUdpClient.BeginReceive(new AsyncCallback(asycRecvCallback), udpRecvState);
recvDone.WaitOne();
Thread.Sleep(20);
}
}
}
private void asycRecvCallback(IAsyncResult iar)
{
UdpState udpState = iar.AsyncState as UdpState;
if (iar.IsCompleted)
{
byte[] recvBytes = udpState.udpclient.EndReceive(iar, ref udpRecvState.ipEndPoint);
string strRecv = ByteToString(recvBytes);
if (recvBytes.Length > 0)
{
this.RecvDataUnPacket(strRecv, recvBytes.Length);
}
recvDone.Set();
}
}
recvUdpClient.Receive
语句呢?为什么要学人家用什么 BeginReceive 呢?这种写法肯定是会让代码非常混乱的。
msdn 的这部分代码很垃圾,它只是说明了 BeginReceive 的语法而已,但是它显然是过于垃圾了。这里不要学 msdn。
异步操作设计,本来就是要减少不必要的资源浪费的(特别地,要充分释放线程占用),怎么可能会是 while+waitone+sleep 这种玩意儿的组合代码呢?public class MySession
{
public ....... client;
public List<byte> datas;
public void StartReceive()
{
this.client.BeginReceive(asycRecvCallback, null);
}
private void asycRecvCallback(IAsyncResult iar)
{
byte[] recvBytes = this.client.EndReceive(iar, ........);
datas.AddRange(recvBytes);
var len = 判断datas中是否有一条完整的消息并返回其字节数();
if(len>0)
{
var command = GetYourString(datas, len);
将datas的前len个字节移除;
ThreadPool.QueueUserWorkitem(h=> 处理命令(command));
}
this.client.BeginReceive(asycRecvCallback, null);
}
}
这里绝对没有什么 while 循环、WaitOne/Set 阻塞、ThreadSleep 阻塞之类的代码。
bool isStop = false;
public Form1()
{
InitializeComponent();
ThreadPool.QueueUserWorkItem(new WaitCallback((obj) =>
{
while (!isStop)
{
string data=Receive();
this.Invoke(new Action(() =>
{
this.Text = data;
}));
}
}));
}
string Receive()
{
Thread.Sleep(1000);
return "模拟返回数据:" + DateTime.Now.ToString();
}
}