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

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


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


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:
Status:
RESOLVED FIXED

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:
line1
line2
line3

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

by executing the exe (compiled using VS) under mono command line i get:
start
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)
      {
         Console.WriteLine("start");
         ReadLines();
         Console.ReadKey();
      }

      static async void ReadLines()
      {
         String result;

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

               if(result != null)
                  Console.WriteLine("line: " + result);
               else
                  break;
            }
         }
      }
   }
}
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 ();
#endif
} 

#if NET_4_5
	Task async_task;
	readonly bool leave_open;
#endif
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):

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

The same error is in StreamWriter.cs/CheckState

====================================================
public override Task<String> ReadLineAsync()
{ 
...
            CheckAsyncTaskInProgress();
            Task<String> task = ReadLineAsyncInternal();
            _asyncReadTask = task;
...
}
 
private void CheckAsyncTaskInProgress()
{ 
...
            if (t != null && !t.IsCompleted) 
                throw
...
}
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

So:
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 ();
to
	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 
519,523d518
<                         return ReadLineInternal();
<                 }
< 
<                 private string ReadLineInternal()
<                 {
590c585
<                       if (async_task != null && !async_task.IsCompleted)
---
>                       if (async_task != null && async_task.IsCompleted)
636c631
<                       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