Why does the "Close" call on a stream behave differently in C# and in Java?
Consider the following scenario, a servlet has been written in Java and once you connect to the servlet, it starts writing to the OutputStream, let's say 10 million bytes, 1 byte at a time.
You have a client program which reads the servlet's response stream and r开发者_Python百科eads say 100 bytes and calls close. Now if your client program is in Java, the streams close immediately and the server stops sending the content, but if the client program is in C#, the close call takes a long time to finish because it apparently waits for server to finish writing all the 10 million bytes.
So, I have two questions on this,
- Why does C# behave differently?
- What can I do to ensure the Close call on the C# stream closes the stream immediately and does not allow the server to keep sending the data?
Any pointers will be greatly appreciated :-)
I'm assuming sockets of some kind here. I would suspect that the Java implementation is simply closing the client socket, possibly causing an error on the server, whilst the C# version is being slightly more friendly to the server and waiting for it to acknowledge a close request. Since the server is busy firing off data, it doesn't get - or at least doesn't process - the close request until it's finished sending.
Think of it this way: somebody at your front door trying to sell you something and won't be interrupted. You can slam the door in their face which shuts them up immediately, or you can wait until they've finished talking and then ask them to leave.
To solve it, perhaps you could create a worker thread that opens the stream, waits for the 100 bytes, then closes. In the meantime your program can do whatever it needs to do while the thread eventually shuts down.
So, I finally figured this out a couple of weeks back and verified it with Microsoft as well. The difference between C# and Java is the fact that in Java close call closes the request/connection as well, while in C#, it doesn't happen unless you follow it up with an xxxRequest.Abort() call. Hope this helps someone else as well.
精彩评论