private void OnReceive(IAsyncResult ar) { try { int bytesRead = socketSend.EndReceive(ar); if (bytesRead > 0) { string message = Encoding.UTF8.GetString(buffer, 0, bytesRead); Receive(); this.myctbtn.Dispatcher.Invoke(new Action( delegate { //int intRecData = int.Parse(message); myctbtn.BtnData =buffer; })); ShowMsg(message); } else { ShowMsg("Server closed the connection"); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } 优化这段代码
时间: 2024-01-19 13:02:47 浏览: 122
TCP_Socket.zip_MFC TCP socket_MFC socket_TCP_Socket.zip_mfc tcp
在OnReceive方法中,我们可以进行以下优化:
1. 将字节数组buffer声明为局部变量,以避免在多个方法之间共享状态。
2. 将委托Action替换为lambda表达式,以使代码更加简洁。
3. 将UI操作放在try语句块的外部,以便在处理异常时也可以正常显示消息。
修改后的代码如下:
```
private void OnReceive(IAsyncResult ar)
{
try
{
byte[] buffer = new byte[1024];
int bytesRead = socketSend.EndReceive(ar);
if (bytesRead > 0)
{
string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Receive();
this.Dispatcher.Invoke(() =>
{
myctbtn.BtnData = buffer;
});
ShowMsg(message);
}
else
{
ShowMsg("Server closed the connection");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
```
阅读全文