Skip to content

ObjectDisposedException in System.Diagnostics.AsyncStreamReader.ReadBufferAsync #44453

Closed

Description

@jairbubbles

Description

We're in the process of switching our net472 WPF application to netcoreapp3.1. So far, it's working great!

But we're receiving crash reports from our users which beta test the .NET Core version. These exceptions are not blocking and we get them from the TaskScheduler.UnobservedTaskException event.

The stack traces are not very good as there's no user code inside it. There are different flavors of it:

System.ObjectDisposedException:
   at System.IO.FileStream.BeginRead (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.IO.Stream+<>c.<BeginEndReadAsync>b__48_0 (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Threading.Tasks.TaskFactory`1.FromAsyncTrim (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.IO.Stream.BeginEndReadAsync (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.IO.FileStream.ReadAsync (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.IO.Stream.ReadAsync (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.IO.FileStream.ReadAsync (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Diagnostics.AsyncStreamReader+<ReadBufferAsync>d__16.MoveNext (System.Diagnostics.Process, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)
System.ObjectDisposedException:
   at System.IO.FileStream.ValidateReadWriteArgs (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.IO.FileStream.Read (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.IO.Stream+<>c.<BeginReadInternal>b__43_0 (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Threading.Tasks.Task`1.InnerInvoke (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Threading.Tasks.Task+<>c.<.cctor>b__274_0 (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.IO.Stream.EndRead (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.IO.FileStream.EndRead (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.IO.Stream+<>c.<BeginEndReadAsync>b__48_1 (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Threading.Tasks.TaskFactory`1+FromAsyncTrimPromise`1.Complete (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable`1+ConfiguredValueTaskAwaiter.GetResult (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Diagnostics.AsyncStreamReader+<ReadBufferAsync>d__16.MoveNext (System.Diagnostics.Process, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)
System.ObjectDisposedException:
   at System.Runtime.InteropServices.SafeHandle.DangerousAddRef (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.StubHelpers.StubHelpers.SafeHandleAddRef (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at Interop+Kernel32.ReadFile (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.IO.FileStream.ReadFileNative (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.IO.FileStream.ReadNative (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.IO.FileStream.ReadSpan (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.IO.FileStream.Read (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.IO.Stream+<>c.<BeginReadInternal>b__43_0 (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Threading.Tasks.Task`1.InnerInvoke (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.IO.Stream.EndRead (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.IO.FileStream.EndRead (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.IO.Stream+<>c.<BeginEndReadAsync>b__48_1 (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Threading.Tasks.TaskFactory`1+FromAsyncTrimPromise`1.Complete (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable`1+ConfiguredValueTaskAwaiter.GetResult (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Diagnostics.AsyncStreamReader+<ReadBufferAsync>d__16.MoveNext (System.Diagnostics.Process, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)

This one might be a different problem:

System.NotSupportedException:
   at System.IO.FileStream.ReadSpan (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.IO.FileStream.Read (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.IO.Stream+<>c.<BeginReadInternal>b__43_0 (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Threading.Tasks.Task`1.InnerInvoke (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.IO.Stream.EndRead (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.IO.FileStream.EndRead (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.IO.Stream+<>c.<BeginEndReadAsync>b__48_1 (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Threading.Tasks.TaskFactory`1+FromAsyncTrimPromise`1.Complete (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Diagnostics.AsyncStreamReader+<ReadBufferAsync>d__16.MoveNext (System.Diagnostics.Process, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)

In any case they all point out to System.Diagnostics.AsyncStreamReader which seems to be only used by System.Diagnostics.Process.
We don't have a clear repro yet but it seems it happens when starting external processes (like explorer.exe).

DisposedException does not seem to be an expected exception as seen here:

private async Task ReadBufferAsync()
{
while (true)
{
try
{
int bytesRead = await _stream.ReadAsync(new Memory<byte>(_byteBuffer), _cts.Token).ConfigureAwait(false);
if (bytesRead == 0)
break;
int charLen = _decoder.GetChars(_byteBuffer, 0, bytesRead, _charBuffer, 0);
_sb!.Append(_charBuffer, 0, charLen);
MoveLinesFromStringBuilderToMessageQueue();
}
catch (IOException)
{
// We should ideally consume errors from operations getting cancelled
// so that we don't crash the unsuspecting parent with an unhandled exc.
// This seems to come in 2 forms of exceptions (depending on platform and scenario),
// namely OperationCanceledException and IOException (for errorcode that we don't
// map explicitly).
break; // Treat this as EOF
}
catch (OperationCanceledException)
{
// We should consume any OperationCanceledException from child read here
// so that we don't crash the parent with an unhandled exc
break; // Treat this as EOF
}

As for the fact the exception is not observed, I guess we never wait for _readToBufferTask which seems to be only here:

internal void WaitUntilEOF()
{
if (_readToBufferTask is Task task)
{
task.GetAwaiter().GetResult();
}
}

Configuration

  • x64
  • .NET Core 3.1.9
  • Windows 10.0.18362

Regression?

  • We don't have those crash reports with the .NET Framework 4.7.2 version of the same application

Activity

  1. added
    untriaged
    on Nov 10, 2020
  2. jairbubbles commented on Nov 10, 2020

    @jairbubbles
    Author

    Important information, it seems the user code provoking htis is not that pretty:

    using (var process = new Process())
    {
        try
        {
            process.StartInfo = processStartInfo;
            process.Start();
        }
        catch (Exception e)
        {
           return;
        }
    
        process.ErrorDataReceived += (s, e) =>
        {
            //
        };
        process.BeginErrorReadLine();
    }

    We're disposing the process while we're still reading the error stream and we don't wait for the process to end.

  3. removed
    untriaged
    on Nov 11, 2020
  4. added this to the 6.0.0 milestone on Nov 11, 2020
  5. stephentoub commented on Nov 13, 2020

    @stephentoub
    Member

    We're in the process of switching our net472 WPF application to netcoreapp3.1. So far, it's working great!

    Great to hear.

    We're disposing the process while we're still reading the error stream and we don't wait for the process to end.

    Thanks, that's helpful. Here:


    we currently catch and eat IOException and OperationCanceledException. In theory we could add more to the list. That said, disposing of objects while they're in use is highly discouraged ;-) and I wouldn't be surprised if you could cause other kinds of exceptions by doing that.

  6. stephentoub commented on Nov 13, 2020

    @stephentoub
    Member

    This one might be a different problem

    That's probably the same thing, and an example of "and I wouldn't be surprised if you could cause other kinds of exceptions by doing that"... when the Process gets disposed of and its streams get disposed of, the stream's CanRead property will then return false, causing a NotSupportedException when trying to read.

  7. stephentoub commented on Nov 13, 2020

    @stephentoub
    Member

    But we're receiving crash reports

    Can you elaborate on this? Why are unobserved exceptions causing crashes? Have you changed the default behavior for TaskScheduler.UnobservedTaskExceptions such that it will crash if one goes unobserved?

  8. jairbubbles commented on Nov 13, 2020

    @jairbubbles
    Author

    Can you elaborate on this? Why are unobserved exceptions causing crashes? Have you changed the default behavior for TaskScheduler.UnobservedTaskExceptions such that it will crash if one goes unobserved?

    I didn't chose the good words, it's not killing the application.

    That's probably the same thing, and an example of "and I wouldn't be surprised if you could cause other kinds of exceptions by doing that"... when the Process gets disposed of and its streams get disposed of, the stream's CanRead property will then return false, causing a NotSupportedException when trying to read.

    Indeed, we fixed the code and we no longer receive any error reports on the subject.

    After we pinpointed the code that was faulty, it was pretty obvious that something wrong was going on with the user code. So I'm wondering what could have been made differently so that we get more info in the exception?

    I'm not sure catching the ObjectDisposedException would be a solution here as it would completely swallow the fact that something is not correct in the user code and as you said "disposing of objects while they're in use is highly discouraged ;-) ".

    That being said, disposing objects is sometimes added later on a code base because for instance a static analyzer told you to do so and one can do the change too quickly without the full picture.

    Should the _readToBufferTask awaited in the dispose (after its being canceled)? I guess we would a better stacktrace in that case?

  9. modified the milestones: 6.0.0, 7.0.0 on Jul 26, 2021
  10. modified the milestones: 7.0.0, Future on Jul 9, 2022
  11. added
    backlog-cleanup-candidate
    on Jul 9, 2022
  12. ghost closed this as completedon Jul 23, 2022
  13. ghost locked as resolved and limited conversation to collaborators on Aug 22, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Diagnostics.Processbacklog-cleanup-candidateno-recent-activity

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions