简体   繁体   中英

NetworkStream.Write asynchronous issue

I have a problem with writing to a NetworkStream in C#. From MSDN i read:

The Write method blocks until the requested number of bytes is sent or a SocketException is thrown

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:

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. 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 ?

The MSDN description should perhaps be better read as

The Write method blocks until the requested number of bytes is written to the local network buffer or a SocketException is thrown

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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