WriteAllTextAsync
和AppendAllTextAsync
方法的大小大于4kb,则无法写入字符串的内容。我假设这是某种缓冲区限制,但是那些方法不支持接受缓冲区大小作为参数的重载方法。我正在使用.net Framework 4.7.2
使用WriteAllText
类的AppendAllText
或File
方法时,输出文件的长度为254 kb,其中写入了全部文本,但使用了这些版本的Async
方法仅写入4kb的输出。
//Populate jsonString variable with a very large string
string jsonString = "placeholder for string content";
//Below code will output partial string till 4kb in length
File.AppendAllTextAsync("temp.json", jsonString);
//Below code outputs the entire content
File.AppendAllText("temp.json", jsonString);
有人可以提供这种行为的解释以及问题的解决方法
答案 0 :(得分:2)
您使用Async调用的方式不正确。当您以这种方式调用File.AppendAllTextAsync
时,将执行新任务。您必须使用关键字await
等待此方法的结果。如果不等待,程序将在异步调用完成并写入不完整的文本之前结束。
正确的电话是:
await File.AppendAllTextAsync("temp.json", jsonString);
答案 1 :(得分:1)
如果您在控制台应用程序中尝试此操作,则该过程可能没有时间编写所有内容。 你可以尝试更换
File.AppendAllTextAsync("temp.json", jsonString);
使用
var task = File.AppendAllTextAsync("temp.json", jsonString);
task.Wait();
?
edit:有关.Wait()或.Result创建死锁的问题在UI线程的上下文中有效。这里不是这种情况。