James
James

Reputation: 2610

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

Upvotes: 2

Views: 3186

Answers (2)

maximpa
maximpa

Reputation: 1988

One of the reasons might be that the file has not been created yet, when the second method tries to read it:

Diagram 1

So, the second method have to wait for the first method to finish:

Diagram 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:

Upvotes: 9

Jennifer Marsman - MSFT
Jennifer Marsman - MSFT

Reputation: 5225

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);

Upvotes: 1

Related Questions