C# 程序在读/写期间冻结
我有一个用 C# 编写的程序,它从磁盘上的文件中读取大量数据,然后输出几行文本,最多可能 100 行到文本文件中。
该程序冻结了大约一半,我是 C# 新手,并且从研究来看,一般编程似乎我需要使用与控制表单的线程不同的线程。有两个问题,
我应该使用一个新线程进行读取,并使用一个新线程进行写入,还是仅使用一个线程进行读取函数?
执行此操作的最佳方法是什么?
我希望这是有道理的,我非常感谢您的帮助!
I have a program written in C#, it does a lot of read from files from the disk and then output a few lines of text, not many possibly 100 at tops into a text files.
The program freezes about half way through, I'm new to c# and programming in general from research it seems that I need to use a separate thread from the one that controls the form. Two questions,
Should I used a new thread for the read and a new one for the write or just one for the read function?
What would be the best way of doing this?
I hope this makes sense and I really appreciate your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
BackgroundWorker 是这里最好用的东西。这是一个很好的教程,其中描述了它的所有事件和属性。
简而言之,这就是您应该做的。
要记住的最重要的事情是 ProgressChanged 和 RunWorkerCompleted 事件是在主线程中执行,您可以使用后台工作结果更新 UI。仅DoWork 事件在后台线程中执行。
BackgroundWorker is the best thing to use here. Here is a good tutorial which describe all of its events and properties.
In brief this is what you should do.
The most important thing to keep in mind is both ProgressChanged and RunWorkerCompleted events are executing in the main thread where you can update the UI by using the background worker results. Only the DoWork event executing in the Background thread.
如果完整读取必须在写入之前发生,则只需要一个线程 - 否则,可以使用两个线程。
查看线程示例:
http://msdn.microsoft.com/en-我们/library/aa645740(v=vs.71).aspx
If the full read must occur before the write, you only need one thread - otherwise, you can use two.
Check this out for a threading example:
http://msdn.microsoft.com/en-us/library/aa645740(v=vs.71).aspx