为什么以下程序在行上返回System.InvalidOperationException"return writer.WriteAsync(hugestring);"?
Why does the following program throw System.InvalidOperationException on the line "return writer.WriteAsync(hugestring);"?
using System.Threading.Tasks; using System.IO; namespace ConsoleApplication7 { public class C { public Task WriteAsync() { var path = @"c:\temp\fail.txt"; File.Delete(path); using (var file = File.OpenWrite(path)) { using (var writer = new StreamWriter(file)) { string hugestring = "0 1 2 3 4 5 6 7 8 9 10 11 12 13 ... 9999 "; // SNIP! The original string was actually 48890 chars long! return writer.WriteAsync(hugestring); } } } public async void writeCaller() { await WriteAsync(); } } class Program { static void Main(string[] args) { C c = new C(); c.writeCaller(); } } }
请注意,hugestring实际上是很多千字节长,但我已经剪掉了内容以方便显示。小(小于2KB)的hugestring值不会引发异常。
Note that hugestring is actually many kilobytes long, but I've snipped out the contents for ease of display. Small (less than 2KB) hugestring values do not throw the exception.
推荐答案
在WriteAsync返回任务之前,您正在关闭StreamWriter已完成。
You're closing the StreamWriter before the Task returned by WriteAsync has completed.
将来,请发布Exception.Message和堆栈跟踪。
In the future, please post the Exception.Message and the stack trace as well.
更多推荐
System.IO.StreamWriter.WriteAsync抛出System.InvalidOperationException
发布评论