Jam*_*mes 2 c# asynchronous windows-8 .net-4.5
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);
Run Code Online (Sandbox Code Playgroud)
file是一个全局变量,CreateFile方法会将"data"写入文件,而Output方法输出它的内容.不幸的是,它并不总是有效,有时,我得到异常,说"对象引用未设置为对象",经过研究,我发现有时候,文件为null,我认为它可能是由Output方法执行的,但是文件创造没有完成.因此,如果我添加断点,它总是有效.任何人都可以帮我在文件创建完成后如何让Output方法执行?
谢谢
其中一个原因可能是文件尚未创建,当第二个方法尝试读取它时:

所以,第二种方法必须等待第一种方法完成:

有几种方法可以实现这一目标.
var task = new Task(() => CreateFile(data));
task.Wait();
Run Code Online (Sandbox Code Playgroud)
另一个,例如,ManualResetEvent类:
ManualResetEvent允许线程通过信令相互通信.通常,此通信涉及一个线程必须在其他线程可以继续之前完成的任务.
其他一些相关链接:
关于Joseph Albahari网站上关于C#多线程的一篇很棒的文章:http://www.albahari.com/threading/
| 归档时间: |
|
| 查看次数: |
2902 次 |
| 最近记录: |