简体   繁体   English

NetworkStream.Write异步问题

[英]NetworkStream.Write asynchronous issue

I have a problem with writing to a NetworkStream in C#. 我在C#中写入NetworkStream时遇到问题。 From MSDN i read: 从MSDN我读到:

The Write method blocks until the requested number of bytes is sent or a SocketException is thrown Write方法将阻塞,直到发送所请求的字节数或抛出SocketException

Well - in my case, it behaves like an asynchronous method. 嗯 - 就我而言,它的行为就像一个异步方法。 Thread is not being blocked. 线程未被阻止。

Here is a code sample, to enlighten situation a bit: 这是一个代码示例,稍微启发一下情况:

TcpClient tcpcl = new TcpClient("192.168.1.128", 1337);
NetworkStream netst = tcpcl.GetStream();
byte[] will_send = File.ReadAllBytes(@"large_file_120_MB.mp4");
Console.WriteLine("Starting transmission...");
netst.Write(will_send, 0, will_send.Length);
Console.WriteLine("File has been sent !");
(... later instructions ...)

Result from console after 1 second of execution: 执行1秒后控制台的结果:

Starting transmission... 开始传输......

File has been sent ! 文件已发送!

Second message shows immediately. 第二条消息立即显示。 Later instructions are being executed. 后来的指令正在执行中。

Meanwhile server still receives the file and on its side everything works well. 同时服务器仍然接收文件,并在其一侧一切正常。 It gets better - if i kill sending program, during transmission, receiving won't stop. 它变得更好 - 如果我杀了发送程序,在传输过程中,接收将不会停止。 Degugger shows clearly that app has ended entirely. Degugger清楚地表明应用已完全结束。 However few more megabytes will still be transmitted, until receiving stops completely. 但是,在完全停止接收之前,仍然会传输更多的兆字节。

So my question - is there a way to block main thread, until Write method is finished ? 所以我的问题 - 有没有办法阻止主线程,直到Write方法完成?

The MSDN description should perhaps be better read as MSDN描述应该更好地理解为

The Write method blocks until the requested number of bytes is written to the local network buffer or a SocketException is thrown Write方法将阻塞,直到请求的字节数写入本地网络缓冲区或抛出SocketException

ie The write will return before the entire file has been successfully received at the other end. 即写入将在另一端成功接收整个文件之前返回。

This also means when you close your application anything currently in the network buffer may continue to be sent. 这也意味着当您关闭应用程序时,可能会继续发送当前在网络缓冲区中的任何内容。

The only way to block the main thread until the entire file has been succesfully received is to potentially use asynchronous sockets and once the send is complete wait until some sort of confirmation is sent by the receiving end, which you would have to implement. 阻止主线程直到成功接收整个文件的唯一方法是可能使用异步套接字,一旦发送完成,等待接收端发送某种确认,您必须实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM