如何使用后台工作者?
我知道它有3种方法。在我的程序中,我有一个发送消息的方法。通常会很晚,并且程序有时根本不发送消息来响应按钮按下。有时,它比我预期晚了 5 秒,程序就会冻结。我想使用 BackgroundWorker
按预期发送消息并允许程序始终正常运行。我有在按钮处理程序中发送消息的代码。现在我应该把这个等效的代码放在哪里?我希望所有这些仍然可以通过按下按钮来处理。
这是合适的处理程序吗?
backgroundWorker1.RunWorkerAsync();
并在:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {}
我要将我的代码放入按钮处理程序中? 之前的内容是:
carga.progressBar1.Minimum = 0;
carga.progressBar1.Maximum = 100;
Carga 是我的另一种形式,ProgressBar 就在其中。在这种情况下如何使用BackgroundWorker?
I know it has 3 methods. In my program I have a method to send a message. It is often late and the program sometimes doesn't send the message at all in response to a button press. At times it is as late as 5 seconds from what I would expect and the program freezes. I want to use a BackgroundWorker
to send the message as expected and allow the program to run normally at all times. I had the code for sending the message in a button handler. Now where do I put this equivalent code? I would like all of this to still be handled by a button press.
Is this the appropriate handler?
backgroundWorker1.RunWorkerAsync();
and in:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {}
I'm going to put my code in the button handler?
And this before:
carga.progressBar1.Minimum = 0;
carga.progressBar1.Maximum = 100;
Carga is my other form where the ProgressBar is. How do I use a BackgroundWorker in this scenario?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您只能从
ProgressChanged
或RunWorkerCompleted
事件处理程序更新进度栏,因为它们与 UI 线程同步。基本思想是。
Thread.Sleep
只是在这里模拟一些工作。将其替换为您真实的路由调用。You can update progress bar only from
ProgressChanged
orRunWorkerCompleted
event handlers as these are synchronized with the UI thread.The basic idea is.
Thread.Sleep
just simulates some work here. Replace it with your real routing call.我知道这有点旧了,但如果另一个初学者正在经历这个,我将分享一些涵盖更多基本操作的代码,这是另一个示例,其中还包括取消过程和报告的选项向用户显示进程的状态。我将在上面的解决方案中添加 Alex Aza 给出的代码
I know this is a bit old, but in case another beginner is going through this, I'll share some code that covers a bit more of the basic operations, here is another example that also includes the option to cancel the process and also report to the user the status of the process. I'm going to add on top of the code given by Alex Aza in the solution above
试试这个:
Try this: