Bug 9761 - InvalidOperationException on StreamReader.ReadLineAsync
Summary: InvalidOperationException on StreamReader.ReadLineAsync
Alias: None
Product: Class Libraries
Classification: Mono
Component: mscorlib ()
Version: unspecified
Hardware: PC Windows
: --- normal
Target Milestone: Untriaged
Assignee: Marek Safar
Depends on:
Reported: 2013-01-24 09:19 UTC by tmuthmann
Modified: 2013-02-01 12:32 UTC (History)
3 users (show)

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

Example Source and exe (3.74 KB, application/zip)
2013-01-24 09:19 UTC, tmuthmann

Notice (2018-05-24): bugzilla.xamarin.com is now in read-only mode.

Please join us on Visual Studio Developer Community and in the Xamarin and Mono organizations on GitHub to continue tracking issues. Bugzilla will remain available for reference in read-only mode. We will continue to work on open Bugzilla bugs, copy them to the new locations as needed for follow-up, and add the new items under Related Links.

Our sincere thanks to everyone who has contributed on this bug tracker over the years. Thanks also for your understanding as we make these adjustments and improvements for the future.

Please create a new report on GitHub or Developer Community with your current version information, steps to reproduce, and relevant error messages or log files if you are hitting an issue that looks similar to this resolved bug and you do not yet see a matching new report.

Related Links:

Description tmuthmann 2013-01-24 09:19:51 UTC
Created attachment 3279 [details]
Example Source and exe

I compiled the following code using VS 2012 and .NET 4.5.

existingfile.txt has follwing lines:

I get the following output using VS:
line: line1
line: line2
line: line3

by executing the exe (compiled using VS) under mono command line i get:
line: line1

Unhandled Exception:
System.InvalidOperationException: Operation is not valid due to the current state of the object
  at System.IO.StreamReader.CheckState () [0x00000] in <filename unknown>:0
  at System.IO.StreamReader.ReadLineAsync () [0x00000] in <filename unknown>:0
  at ConsoleApplication.Program+<ReadLines>d__0.MoveNext () [0x00000] in <filename unknown>:0

I tested Mono 3.0.3, 3.0.2, 3.0.1 and 2.11.4 using the Mono Installers under Windows 7/64.
The same with Mono 3.0.3 under OpenSuse 11.4 using the Mono rpms.

So ReadLineAsync() is blocked after getting the first line.
using System;
using System.IO;

namespace ConsoleApplication
   class Program
      static void Main(string[] args)

      static async void ReadLines()
         String result;

         using(StreamReader reader = File.OpenText("existingfile.txt"))
               result = await reader.ReadLineAsync();

               if(result != null)
                  Console.WriteLine("line: " + result);
Comment 1 tmuthmann 2013-01-24 10:21:27 UTC
I looked into the Mono Sources and found mcs\class\corlib\System.IO\StreamReader.cs

On ReadLineAsync the new task is saved to async_task.
As there is no mechanism to clear async_task, the next call to ReadLineAsync 
calls CheckState and from there the Exception:

	if (async_task != null && async_task.IsCompleted)
		throw new InvalidOperationException ();

Why do you save the new task in Mono?
I think this should be done only by the caller doing:
var newtask = reader.ReadLineAsync();
await newtask;
No need to save in in Mono.
On every call to ReadLineAsync a new Task must be generated.
This will be done if you remove async_task completely from the source.

public override Task<string> ReadLineAsync ()
	CheckState ();

	Task<string> res;
	async_task = res = base.ReadLineAsync ();
	return res;

void CheckState ()
	if (base_stream == null)
		throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");

#if NET_4_5
	if (async_task != null && async_task.IsCompleted)
		throw new InvalidOperationException ();

#if NET_4_5
	Task async_task;
	readonly bool leave_open;
Comment 2 tmuthmann 2013-01-24 11:58:14 UTC
My above comment to delete async_task is not correct.
I looked in the .NET 4.5 sources and found the code below.
As you can see similar code, except the negation before t.IsCompleted.
So the patch for my Bug is (in StreamReader.cs/CheckState):

    if (async_task != null && async_task.IsCompleted)
    if (async_task != null && !async_task.IsCompleted)

The same error is in StreamWriter.cs/CheckState

public override Task<String> ReadLineAsync()
            Task<String> task = ReadLineAsyncInternal();
            _asyncReadTask = task;
private void CheckAsyncTaskInProgress()
            if (t != null && !t.IsCompleted) 
Comment 3 tmuthmann 2013-01-24 13:33:24 UTC
Ok, next time i try it before submitting a patch.
I compiled Mono 3.0.3 on my OpenSuse System and got a problem with the patch.

    async_task = res = base.ReadLineAsync ();

calls TextWriter.ReadLineAsync:
public virtual Task<string> ReadLineAsync ()
	return Task.Factory.StartNew (l => ((TextReader) l).ReadLine (), this);

and from there the overridden ReadLine to StreamReader.ReadLine
First in there is another CheckState, which fails because the newly generated Task is NOT completed.
Exact for this reason .NET calls a private function and not ReadLine.

So in ADDITION to my above fix we must create StreamReader.ReadLineInternal with the content of StreamReader.ReadLine, without the CheckState

public override string ReadLine()
	CheckState ();

	return ReadLineInternal();

private string ReadLineInternal()
	remainings of  the old ReadLine

We must call ReadLineInternal from ReadLineAsync, so we cannot call the Parent:
in ReadLineAsync from
	async_task = res = base.ReadLineAsync ();
	async_task = res = Task.Factory.StartNew (l => ((StreamReader) l).ReadLineInternal (), this); 

Below is a Patch for the 3.0.3 Source, only for ReadLineAsync.
But all Async Functions in StreamReader and StreamWriter have the same problem.
So see this patch only as a proof of concept, as it works on my system.

diff StreamReader.cs StreamReader.cs.org 
<                         return ReadLineInternal();
<                 }
<                 private string ReadLineInternal()
<                 {
<                       if (async_task != null && !async_task.IsCompleted)
>                       if (async_task != null && async_task.IsCompleted)
<                       async_task = res = Task.Factory.StartNew (l => ((StreamReader) l).ReadLineInternal (), this);
>                       async_task = res = base.ReadLineAsync ();
Comment 4 Marek Safar 2013-02-01 12:32:29 UTC
Fixed in master