后台辅助角色多次运行 doWork

本文关键字:运行 doWork 角色 后台 | 更新日期: 2023-09-27 18:31:02

private void button_uploadToPI_Click(object sender, RoutedEventArgs e)
    {

        this.newFilePath = this.textbox_input_filePath.Text;
        this.label_status.Content = "";
        if (bgWorker.IsBusy != true)
        {

            bgWorker.RunWorkerAsync();
        }
    }

这是我的点击事件。

public MainWindow()
    {
        InitializeComponent();
        this.progressBar.Minimum = 0;
        this.progressBar.Maximum = 100;
        this.bgWorker = new BackgroundWorker();
        this.bgWorker.WorkerReportsProgress = true;
        this.bgWorker.WorkerSupportsCancellation = true;
        reader.IsOpen = false;
        this.bgWorker.DoWork += bgWorker_DoWork;
        this.bgWorker.ProgressChanged += bgWorker_ProgressChanged;
        this.bgWorker.RunWorkerCompleted += bgWorker_RunWorkerCompleted;
    }

主窗口方法。

public partial class MainWindow : Window
{
    private BackgroundWorker bgWorker;

bgWorker 在此处初始化。

void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        this.progressBar.Value = 0;
        this.label_progressPercentage.Content = "0%";
        reportTextBox.ScrollToEnd();
    }

运行工作完成代码

主要问题是,如果我运行一次应用程序,它会按预期工作。如果我再次单击,它将执行该方法两次,如果我再次单击它,它将执行该方法 3 次。将增加每次新点击。

任何人都可以在这里看到主要问题吗?

后台辅助角色多次运行 doWork

我反对@galenus建议的一个样本。我在后台工作线程上遇到了同样的情况,单击"执行工作"按钮多次触发 dowork,直到我使用该按钮初始化工作线程。代码块:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Data;
namespace MouseClick
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();
        }
        public BackgroundWorker worker = new BackgroundWorker();
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //e.Handled = true; // Din't do anything 
            worker = new BackgroundWorker(); //stopped the dowork being executed multiple times when button pressed again in the same session
            worker.WorkerReportsProgress = true;
            worker.WorkerSupportsCancellation = true;
            worker.DoWork += worker_DoWork;
            worker.ProgressChanged += worker_ProgressChanged;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
            worker.RunWorkerAsync();
        }
        void worker_DoWork(object sender, DoWorkEventArgs e)
        {

            int tot = 1;
            MessageBox.Show(tot.ToString()); //if this message box appears multiple times, it means the dowork is executing multiple times
            DataTable dt = new DataTable();
            dt.Columns.Add("Running Number");
            for (int i = 0; i <= 100; i++)
            {
                if (worker.CancellationPending == true)
                {
                    //http://stackoverflow.com/questions/8300799/cancel-background-worker-exception-in-e-result
                    //  e.Cancel = true; //This does the trick
                    e.Result = 100;
                    return;
                }
                worker.ReportProgress(i);
                System.Threading.Thread.Sleep(1);
                dt.Rows.Add(i);
            }
            e.Result = dt;
        }
        #region "worker_ProgressChanged"
        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
        }
        #endregion
        #region "worker_RunWorkerCompleted"
        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            myGrid.ItemsSource = ((DataTable)e.Result).DefaultView;
            worker.Dispose();
        }
        #endregion
    }
}

虽然这可能有效,但您可以在 MainWindow 的构造函数中声明和初始化 worker,之后您还可以附加事件。这样,在Button_Click方法中,您只需要运行工作线程即可。无需在每次单击按钮时创建新工作线程并附加这些事件,您可以节省一些时间;)

@M00给出了正确的答案。您必须定义一次 DoWork 和 RunworkerComplete。我写了一个例子,你可以看看。

    BackgroundWorker TaraBW = new BackgroundWorker();   
    private void Form1_Load(object sender, EventArgs e)
    {
        TaraBW.DoWork += Tara;
        TaraBW.RunWorkerCompleted += TaraSon;
    }
    
    private void button6_Click(object sender, EventArgs e)
    {
        //If you write it here "DoWork" and "RunworkerCompleted",will branching occurs.
        TaraBW.RunWorkerAsync();
        
    }
    private void Tara(object sender, DoWorkEventArgs e)
    {
        StreamWriter SW = new StreamWriter(Application.StartupPath + @"'3dPC.xyz");
        for (int j = 0; j < 10000000; j++)
        {
            SW.WriteLine(Convert.ToString(j + " " + j + 1 + " " + j + 2));
        }
        SW.Close();
    }
    private void TaraSon(object sender, RunWorkerCompletedEventArgs e)
    {
        MessageBox.Show("Finish");
    }