首页 > 解决方案 > TcpClient sometimes seems not to finish a writing before closing/disposing. Why?

问题描述

given is this simplified code:

class SenderFactory
{
  public TcpSender ConnectSender( IPEndPoint ipEndPoint )
  {
    TcpClient client = new TcpClient();
    client.NoDelay = true;
    client.Connect( ipEndPoint );
    return new TcpSender( client );
  }
}

class TcpSender : IDisposable
{
  TcpClient client;
  NetworkStream stream;

  public void TcpSender( TcpClient client )
  {
    this.client = client;
  }

  public void Send( byte[] data )
  {
    stream = client.GetStream();
    stream.Write( data, 0, data.Length );
  }

  public void Dispose()
  {
    stream?.Close();
    stream?.Dispose();
    client?.Close();
    client?.Dispose();  
  }
}

class Test
{
  void Test()
  {
    using(TcpSender sender = factory.ConnectSender( ipEndPoint ))
    {
      // every data is only around 20 bytes
      sender.Send( data1 );
      sender.Send( data2 );
      sender.Send( data3 );
      sender.Send( data4 );
      // Thread.Sleep(10); It always works with this sleep
    }
  }
}

I am sending a few commands to the endpoint (The endpoint is a hardware device whose code I have no access to). The device can only handle one command at a time.

The code works like 80-90% of the time (device receives the data and displays it), but sometimes it just seems it does not receive the data (because it does not display it). It always works if I do this ugly Thread.Sleep(10) before disposing.

Does anyone have a clue what this could be? Maybe the closing/disposing of the stream/client is too fast in some random cases? What would be a better approach to fix this?

Thank you!

标签: tcptcpclientdispose

解决方案


推荐阅读