如何在主要形式中取消backgroundWorker其他形式

时间:2019-10-09 09:31:40

标签: c# winforms backgroundworker

我需要从另一种形式启动的主形式中取消BakgroundWorker。我正在代表们的帮助下解决这个问题。但是,我无法撤消BakgroundWorker。帮助解决此问题。如果还有其他解决方案,请写信。

例如,我给出主要形式的代码

public partial class MainForm : Form
{
    public MainForm(string FIO)
    {
       //some code
    }

    public event EventHandler<EventArgs> Canceled;

    private void Button5_Click(object sender, EventArgs e)
    {
       if (Canceled != null)
           Canceled(sender, e);
    }
}

backgroundWorker启动时的表单代码

public partial class CarriageForm : Form
{
    public CarriageForm(ToolStripProgressBar toolStripProgressBar1, ToolStripLabel toolStripLabel1)
    {
        //some code
    }

private void CarriageForm_Load(object sender, EventArgs e)
{
    progBar.Visible = false;

    if (!backgroundWorker1.IsBusy)
    {
        progBar.Visible = true;
        progBar.Maximum = GetTotalRecords();
        string GetCarriage = "Select dc.ID, dc.CarNumber [Номер вагона],dc.AXIS [Осность],do.ID [OwnerID], do.Name [Собственник],do.FullName [Собственник полное наименование] From d__Carriage dc Left Join d__Owner do on do.ID = dc.Owner_ID";

        MainForm mainForm = new MainForm(null);
        mainForm.Canceled += new EventHandler<EventArgs>(Button2_Click);

        backgroundWorker1.RunWorkerAsync(GetCarriage);
    }

    //BackgroundWorker1_DoWork...

    //BackgroundWorker1_ProgressChanged...

    //BackgroundWorker1_RunWorkerCompleted..

public void Button2_Click(object sender, EventArgs e)
        {
            if (backgroundWorker1.WorkerSupportsCancellation == true)
            {
                // Stop the Background Thread execution
                Application.UseWaitCursor = false;
                System.Windows.Forms.Cursor.Current = Cursors.Default;
                backgroundWorker1.CancelAsync();
                progBar.Value = 0;
                progBar.Visible = false;
                TlStpLabel.Text = "Пользователь умышленно отменил";
            }
        }
}

为清楚起见

enter image description here

0 个答案:

没有答案