求助:C# socket异步通信,大量消息卡在SendAsync之后,回调方法之前
模拟450个用户移动,发送移动消息,实际不到450人的时候,服务端发送消息已经卡的比较厉害了,具体表现为消息已经调用SendAsync方法,但是没有触发回调。所以SocketAsyncEventArgs对象已经消息体都驻留在内存中,导致内存不断变大。
发送以及统计部分代码:
Interlocked.Increment(ref totalCount); //总计发送消息数量 +1
Interlocked.Increment(ref currentCount);//等待发送消息 +1
bool willRaiseEvent = _acceptedSocket.SendAsync(sendEventArgs);
if (!willRaiseEvent){
ProcessSend(sendEventArgs);
}
回调部分代码方法:
private void ProcessSend(SocketAsyncEventArgs e){
try{
Interlocked.Decrement(ref currentCount);//发送成功后 -1
var bufferLength = (int) (e.UserToken);
int count = e.BytesTransferred;
SocketError error = e.SocketError;
if (error != SocketError.Success){
//string ip = RemoteEndPoint.ToString();
//Log.Error(string.Format("发送消息异常,SocketError:{0},远程地址:{1}", error, ip));
_segementBufferManager.FreeBufferListAndEventArgs(e, SendEventArgsCompleted);
SafeCloseSocket();
FireConnectionErrorAsync(new SocketException((int) (error)), TcpConnectionErrorType.EndSend);
return;
}
统计消息有一个timer每300毫秒打印一次,该部分代码:
int nWorkThreads, nIOThreads;
ThreadPool.GetAvailableThreads(out nWorkThreads, out nIOThreads);
LogWriter.Error(Guid.Empty, 2, string.Format("消息总计:{0},等待发送:{1},空闲工作线程:{2},空闲io线程:{3}", TcpConnection.totalCount, TcpConnection.currentCount, nWorkThreads, nIOThreads));
模拟450个用户移动,发送移动消息,实际不到450的时候,服务端发送消息已经卡的比较厉害了。
实际测试的结果:
[2013-05-24 13:09:48,290]消息总计:14241,等待发送:5273,可用工作线程:32765,可用io线程:1000
[2013-05-24 13:09:48,602]消息总计:14331,等待发送:5327,可用工作线程:32766,可用io线程:1000
[2013-05-24 13:09:48,915]消息总计:14344,等待发送:5335,可用工作线程:32766,可用io线程:1000
网络带宽:10Gbps,毫无压力;cpu 毫无压力,内存因为消息积压,会不断增长。