简体   繁体   中英

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. 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. 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. 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?

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 allows threads to communicate with each other by signaling. 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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