如何阻止后台工作程序触发RunWorkerCompleted事件

时间:2016-01-18 11:27:04

标签: c# .net events backgroundworker

我使用后台工作人员非常新,我尝试做的是加载一个表示"发送文件"然后当它完成那个表格但我不知道如何打电话或关闭后台工作人员。我所拥有的是以下代码:

bwSendingFiles.RunWorkerAsync();

switch (dgvFile.SelectedRows[0].Cells[1].Value.ToString().Trim())
{
     case "S":
         SendFile.FilesSFTP_FTP();
         break;
      case "F":
         SendFile.FilesSFTP_FTP();
         break;
      case "E":
         SendFile.SendFileEmail();
         break;
}

bwSendingFiles.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bwSendingFiles_RunWorkerCompleted);

这就是我在活动中所拥有的:

private void bwSendingFiles_DoWork(object sender, DoWorkEventArgs e)
{
    formOpen = new SendingScreen();
    formOpen.ShowDialog();            
}

private void bwSendingFiles_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{                        
    formOpen.Close();            
}

完成方法后,如何停止后台工作程序?

1 个答案:

答案 0 :(得分:1)

几点:

  • DoWork方法在另一个线程上执行,而DoWork完成后在主线程上触发RunWorkerCompleted方法;

  • 我要说你应该在主(UI)线程上创建formOpen,然后在主线程上工作(发送文件)。您不应该直接从不同的线程对UI元素执行操作,而是使用BeginInvoke方法:

    formOpen.BeginInvoke(new Action(() =>
    {
        formOpen.Close();
    }));
    

我会更喜欢这样做:

bwSendingFiles.DoWork += new RunWorkerCompletedEventHandler(bwSendingFiles_DoWork);
bwSendingFiles.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bwSendingFiles_RunWorkerCompleted);
formOpen = new SendingScreen();
formOpen.ShowDialog();

bwSendingFiles.RunWorkerAsync(dgvFile.SelectedRows[0].Cells[1].Value.ToString().Trim());

private void bwSendingFiles_DoWork(object sender, DoWorkEventArgs e)
{
    var arg = (string)e.Argument
    switch (arg)
    {
        case "S":
            SendFile.FilesSFTP_FTP();
            break;
        case "F":
            SendFile.FilesSFTP_FTP();
            break;
        case "E":
            SendFile.SendFileEmail();
            break;
    }
}

private void bwSendingFiles_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{                        
    formOpen.Close();            
}