C# - 接收数据时的事件和委托

当我从服务器接收数据时,我想显示一个字符串。为此,我正在考虑使用委托和事件。我是这个主题的新手(代表和事件),所以我无法设置它。这是我所做的:


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();

}


白猪掌柜的
浏览 272回答 2
2回答

Helenr

你可以写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){}
打开App,查看更多内容
随时随地看视频慕课网APP