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:
So, the second method have to wait for the first method to finish:
There are several ways to achieve that.
One of them would be using Task Class from Task Parallel Library and its Wait Method:
Another one, for example, ManualResetEvent Class:
A few other related links:
A great article on Joseph Albahari’s website about multithreading in C#: http://www.albahari.com/threading/
C# Frequently Asked Questions: Using Async for File Access