当我从服务器接收数据时,我想显示一个字符串。为此,我正在考虑使用委托和事件。我是这个主题的新手(代表和事件),所以我无法设置它。这是我所做的:public delegate void ClientHandleData(byte[] data, int bytesRead);public event ClientHandleData OnDataReceived;public void ConnectToServer(string ipAddress, int port){ this.port = port; tcpClient = new TcpClient(ipAddress, port); clientStream = tcpClient.GetStream(); Thread t = new Thread(new ThreadStart(ListenForData)); started = true; t.Start();}private void ListenForData(){ int bytesRead; while (started) { bytesRead = 0; try { bytesRead = clientStream.Read(buffer.ReadBuffer, 0, readBufferSize); } catch { //A socket error has occurred MessageBox.Show("A socket error has occurred); break; } if (OnDataReceived != null) { // display string to a textbox on the UI } Thread.Sleep(15); } started = false; Disconnect();}
2 回答
Helenr
TA贡献1780条经验 获得超3个赞
你可以写
OnDataReceived?.Invoke(buffer.ReadBuffer, bytesRead);
如果你想确保你的事件不会被设置null在if语句之后,你可以这样做:
var handler = OnDataReceived;
handler?.Invoke(buffer.ReadBuffer, bytesRead);
更新 UI 时要小心,因为您只能从 UI 线程更新 UI。如果您使用的是 WPF,您可以这样做:
Dispatcher.Invoke(() => {
// Update your UI.
});
还要确保有人确实订阅了该事件:
public void Foo()
{
objectWithTheEvent.OnDataReceived += OnOnDataReceived;
}
private void OnOnDataReceived(byte[] data, int count)
{
}
- 2 回答
- 0 关注
- 271 浏览
添加回答
举报
0/150
提交
取消