我创建了一个单线程 Windows 应用程序,它与 100 多个套接字(使用 AsyncCallbacks)进行通信,每秒可能是 5-10 个套接字。
当我从 .NET IDE 启动时,该应用程序运行良好。如果从可执行文件启动,该应用程序似乎被挂起。在进一步的研究中,我发现应用程序在套接字上通信非常好,只有 UI 上的数据没有刷新。似乎应用程序太忙了,无法从套接字读取而不是刷新 UI。
应用程序在用每个套接字的单独线程替换 AsyncCallback 时工作正常,但这似乎不是一个好方法。
我尝试创建消息队列,但没有帮助。
我说应用程序忙于在套接字上读取而不是刷新 UI 是否正确?我该如何解决这个问题?
下面提到了我用于 AsynCallBack 的代码。
private void ConnectSocket()
{
IPEndPoint ipEnd = new IPEndPoint(_ip, _port);
m_socket = new Socket(ipEnd.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
m_socket.Blocking = false;
m_socket.ReceiveBufferSize = RECEIVE_BUFFER_SIZE;
m_socket.NoDelay = true;
m_socket.LingerState = new LingerOption(false, 0);
AsyncCallback onconnect = new AsyncCallback(OnConnect);
m_socket.BeginConnect(ipEnd, onconnect, m_socket);
}
private void OnConnect(IAsyncResult ar)
{
Socket sock = (Socket)ar.AsyncState;
try
{
sock.EndConnect(ar);
if (sock.Connected)
{
SetupReceiveCallback(sock);
}
}
catch (Exception ex)
{
}
}
private void SetupReceiveCallback(Socket sock)
{
try
{
AsyncCallback receiveData = new AsyncCallback(ReceiveData);
sock.BeginReceive(receivedBuffer, 0, receivedBuffer.Length,
SocketFlags.None, receiveData, sock);
}
catch (SocketException ex)
{
}
catch (Exception ex)
{
}
}
private void ReceiveData(IAsyncResult ar)
{
Socket sock = (Socket)ar.AsyncState;
try
{
int numBytesReceived = sock.EndReceive(ar);
if (numBytesReceived > 0)
{
if (OnReceivedData != null)
{
OnReceivedData(receivedBuffer);
}
}
SetupReceiveCallback(sock);
}
catch (SocketException ex)
{
//If error code is 1054 then socket connection is terminated from the client.
}
catch (Exception ex)
{
}
}