Bug 8886 - Exceptions thrown while writing or reading a System.Net.WebConnectionStream can lead to a hang when calling Dispose
Summary: Exceptions thrown while writing or reading a System.Net.WebConnectionStream c...
Status: NEW
Alias: None
Product: Class Libraries
Classification: Mono
Component: System (show other bugs)
Version: 2.10.x
Hardware: Macintosh Mac OS
: --- normal
Target Milestone: Untriaged
Assignee: Bugzilla
URL:
Depends on:
Blocks:
 
Reported: 2012-12-11 14:22 UTC by Mark
Modified: 2012-12-11 18:21 UTC (History)
1 user (show)

See Also:
Tags:
Is this bug a regression?: ---
Last known good build:


Attachments

Description Mark 2012-12-11 14:22:18 UTC
An exception can occur while writing to a stream, specifically a WebConnectionStream, for instance while copying from another stream.  When this happens, we find that our thread will hang while calling Dispose on the WebConnectionStream because it appears to be waiting on the "pending" ManualResetEvent therein to get signaled, which it never does.  We set SendChunked to true, which causes the WebConnectionStream to use the "pending" event to keep track of pending reads/writes so that for instance during close/dispose it can wait before sending the null chunk to indicate that the transfer is complete.  If an exception is thrown in the right place, the "pending" event may never get signaled and this would lead to the hung thread.  I believe a similar problem can happen if a read fails.

In the following code if an exception is thrown during the CopyStream we will leave the "using" block, and dispose will be automatically called, and then the thread will hang indefinitely in WebConnectionStream.Dispose while calling WaitHandle.WaitOne():

using(Stream requestStream = request.GetRequestStream())
{
   CopyStream(responseStream, requestStream);
}

At this time I believe a workaround is to not use the using statement and avoid calling dispose on the stream anywhere else unless there was no write exception.  Looking at the mono source code, there does not appear to be any negative implications to not calling Dipose/Close on the stream, at least it doesn't appear to leak any resources.
Comment 1 Mark 2012-12-11 18:21:26 UTC
Upon further analysis it appears that WebConnectionStream::EndWrite does decrement pendingWrites correctly and set the pending event appropriately when an exception is thrown, but when the exception is rethrown WriteCallbackWrapper eats the exception.  Since this is all handled asynchronously, the original thread that started the stream writing is not immediately notified of the exception.  That thread is allowed to attempt to write at least one additional time before receiving its exception and bailing.  The problem here is that now the second write attempt has incremented pendingWrites to 1 and the pending event has now been reset, so that now if Dispose is called it will hang.

Note You need to log in before you can comment on or make changes to this bug.