如何使用 BackgroundWorker?

How to use a BackgroundWorker?(如何使用 BackgroundWorker?)

本文介绍了如何使用 BackgroundWorker?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道它有 3 种方法.在我的程序中,我有一种发送消息的方法.通常很晚,程序有时根本不发送消息以响应按钮按下.有时它比我预期的要晚 5 秒,程序就会冻结.我想使用 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();

进入:

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 是我在 ProgressBar 所在的另一种形式.在这种情况下如何使用 BackgroundWorker?

Carga is my other form where the ProgressBar is. How do I use a BackgroundWorker in this scenario?

推荐答案

您只能从 ProgressChangedRunWorkerCompleted 事件处理程序更新进度条,因为它们与 UI 同步线程.

You can update progress bar only from ProgressChanged or RunWorkerCompleted event handlers as these are synchronized with the UI thread.

基本思想是.Thread.Sleep 只是在这里模拟一些工作.将其替换为您的真实路由调用.

The basic idea is. Thread.Sleep just simulates some work here. Replace it with your real routing call.

public Form1()
{
    InitializeComponent();

    backgroundWorker1.DoWork += backgroundWorker1_DoWork;
    backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
    backgroundWorker1.WorkerReportsProgress = true;
}

private void button1_Click(object sender, EventArgs e)
{
    backgroundWorker1.RunWorkerAsync();
}

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(1000);
        backgroundWorker1.ReportProgress(i);
    }
}

private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

这篇关于如何使用 BackgroundWorker?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何使用 BackgroundWorker?

基础教程推荐