简体   繁体   English

编写和读取文件异步

[英]Writing and Reading file async

I want to write some content into a local file and then represent it in a textblock. 我想将一些内容写入本地文件,然后将其表示在文本块中。 I have two methods, CreateFile and Output, the first method uses WriteTextAsync method to write content into file, and the second method uses ReadTextAsync method to read the content. 我有两个方法,CreateFile和Output,第一个方法使用WriteTextAsync方法将内容写入文件,第二个方法使用ReadTextAsync方法读取内容。 I called the two methods one by one, like 我一个接一个地调用这两个方法,比如

CreateFile(data);
Output(file);

file is a global variable, CreateFile method will write the “data” into file, and Output method output the content of it. file是一个全局变量,CreateFile方法会将“data”写入文件,而Output方法输出它的内容。 Unfortunately, it not always work, sometimes, I got exception which said “Object reference not set to an object”, after researching, I found sometimes, the file is null, I think it may caused by Output method is executed, but the file creating doesn't complete. 不幸的是,它并不总是有效,有时,我得到异常,说“对象引用未设置为对象”,经过研究,我发现有时候,文件为null,我认为它可能是由Output方法执行的,但是文件创造没有完成。 So if I add a breakpoint, it always works. 因此,如果我添加一个断点,它总是有效。 Anyone can help me how to let the Output method execute after the file creating completed? 任何人都可以帮我在文件创建完成后如何让Output方法执行?

Thanks 谢谢

One of the reasons might be that the file has not been created yet , when the second method tries to read it: 其中一个原因可能是文件尚未创建 ,当第二个方法尝试读取它时:

图1

So, the second method have to wait for the first method to finish : 所以,第二种方法必须等待第一种方法完成

图2

There are several ways to achieve that. 有几种方法可以实现这一目标。

One of them would be using Task Class from Task Parallel Library and its Wait Method : 其中一个将使用任务并行库中的 任务类及其等待方法

var task = new Task(() => CreateFile(data));
task.Wait();

Another one, for example, ManualResetEvent Class : 另一个,例如, ManualResetEvent类

ManualResetEvent allows threads to communicate with each other by signaling. ManualResetEvent允许线程通过信令相互通信。 Typically, this communication concerns a task which one thread must complete before other threads can proceed. 通常,此通信涉及一个线程必须在其他线程可以继续之前完成的任务。

A few other related links: 其他一些相关链接:

Since your methods call asynchronous methods, a simple fix is to call your methods like this: 由于您的方法调用异步方法,一个简单的解决方法是调用您的方法,如下所示:

await CreateFile(data);   // This waits for the method to complete before continuing.  
Output(file);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM