System.IO.StreamWriter.WriteAsync抛出System.InvalidOperationException

编程入门 行业动态 更新时间:2024-10-27 22:25:42
本文介绍了System.IO.StreamWriter.WriteAsync抛出System.InvalidOperationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

为什么以下程序在行上返回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

本文发布于:2023-11-15 19:53:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1597473.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:抛出   IO   System   StreamWriter   InvalidOperationException

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!