I am looking for feedback to perfect my code developed for WPF in terms of speed, stability and resiliency. My code is supposed to handle synchronous status polling as well as asynchronous Commands to numerous TCP servers (more than 20). I am using a BlockingCollection to funnel these Polls & Commands and using the APM Pattern for Socket Communication. Please review.
ManualResetEvent connect = new ManualResetEvent(false);
ManualResetEvent send = new ManualResetEvent(false);
ManualResetEvent receive = new ManualResetEvent(false);
BlockingCollection<string[]> cmd_Queue = new BlockingCollection<string[]>();
...
Task.Run(() => TCP_Comms());
...
void TCP_Comms()
{
while (true)
{
while (wifi_state)
{
string[] frame = cmd_Queue.Take(); // string[] { IP, Command }
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
client.BeginConnect(frame[0], port, new AsyncCallback(Connect_Callback), client);
if (!connect.WaitOne(timeout_Millis)) //1000ms
{
Debug("Connection timeout");
}
else
{
data = Encoding.ASCII.GetBytes(frame[1]);
client.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(Send_Callback), client);
if (!send.WaitOne(timeout_Millis))
{
Debug("Send timeout");
}
else
{
var response = new byte[client.ReceiveBufferSize];
client.BeginReceive(response, 0, response.Length, SocketFlags.None, new AsyncCallback(Receive_Callback), client);
if (!receive.WaitOne(timeout_Millis))
{
Debug("Receive timeout");
}
else
{
string response_data = Encoding.ASCII.GetString(response, 0, response.Length);
Debug("Response Received: " + response_data);
}
}
}
}
catch (SocketException ex)
{
Debug("Comms Error: " + ex.Message);
}
connect.Reset();
send.Reset();
receive.Reset();
client.Close();
}
}
}
void Connect_Callback(IAsyncResult ar)
{
try
{
client.EndConnect(ar.AsyncState as Socket);
connect.Set();
}
catch (Exception ex)
{
Debug("Connect Error: " + ex.Message);
}
}
void Send_Callback(IAsyncResult ar)
{
try
{
client.EndSend(ar.AsyncState as Socket);
Debug("Send Success");
send.Set();
}
catch (Exception ex)
{
Debug("Send Error: " + ex.Message);
}
}
void Receive_Callback(IAsyncResult ar)
{
try
{
client.EndReceive(ar.AsyncState as Socket);
Debug("Receive Success");
receive.Set();
}
catch (Exception ex)
{
Debug("Recieve Error: " + ex.Message);
}
}