C# 程序在读/写期间冻结

发布于 2024-11-07 21:34:47 字数 267 浏览 0 评论 0原文

我有一个用 C# 编写的程序,它从磁盘上的文件中读取大量数据,然后输出几行文本,最多可能 100 行到文本文件中。

该程序冻结了大约一半,我是 C# 新手,并且从研究来看,一般编程似乎我需要使用与控制表单的线程不同的线程。有两个问题,

  1. 我应该使用一个新线程进行读取,并使用一个新线程进行写入,还是仅使用一个线程进行读取函数?

  2. 执行此操作的最佳方法是什么?

我希望这是有道理的,我非常感谢您的帮助!

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,

  1. Should I used a new thread for the read and a new one for the write or just one for the read function?

  2. What would be the best way of doing this?

I hope this makes sense and I really appreciate your help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蘑菇王子 2024-11-14 21:34:47

BackgroundWorker 是这里最好用的东西。这是一个很好的教程,其中描述了它的所有事件和属性。

简而言之,这就是您应该做的。

  1. 创建后台工作实例并设置适当的 属性根据您的需要。
  2. 将所有 I/O 处理代码添加到 DoWork 它将在单独的线程中执行。
  3. 将处理 I/O 操作后要执行的所有逻辑添加到 RunWorkerCompleted 它将在主线程中执行。在这里你可以更新你的 UI 或者在主线程中做你想做的事情。 (您可以通过 RunWorkerCompletedEventArgs.Result 属性访问结果)

要记住的最重要的事情是 ProgressChangedRunWorkerCompleted 事件是在主线程中执行,您可以使用后台工作结果更新 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.

  1. Create a background worker instance and set appropriate properties as you need.
  2. Add all the I/O processing code to the DoWork which will be executed in a separate thread.
  3. Add all the logics that you want to execute after processing I/O operation to the RunWorkerCompleted which will be executed in the main thread. Here you can update your UI or do what ever you want to do in the main thread. (You can access the result through the RunWorkerCompletedEventArgs.Result property)

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.

水溶 2024-11-14 21:34:47

如果完整读取必须在写入之前发生,则只需要一个线程 - 否则,可以使用两个线程。

查看线程示例:
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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文