tcp - 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!
解决方案
推荐阅读
- asp.net - 带计时器的更新面板保持自动滚动页面
- php - SQL:如何通过关注者找到类似的博客
- openedge - 我想使用 match 以便它匹配在模式之间或单词开头有空格或空格的特定模式
- android - recyclerView (kotlin) 的一项中的 4 个可点击视图
- laravel - 如何在 Laravel 中保存 iframe 内容?
- html - 如何在图像上添加文本并添加段落将使用 html、css 在同一行开始
- reactjs - 将 Material-ui 图标放在圆形进度指示器内
- r - 如果 NULL 或满足条件,则在 R 中继续
- command-line - 选择第 3 行并显示第 3 行 TextFile BatchScript
- python - Python中使用Eratosthenes筛子的质数