为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用背景工作器?

如何使用背景工作器?

C#
米脂 2019-07-06 16:39:42
如何使用背景工作器?我知道它有三种方法。在我的程序中,我有一个发送消息的方法。通常是很晚,程序有时根本不发送信息,以响应按钮按下。有时,与我所期望的相比,它已经晚到了5秒,程序冻结了。我想用BackgroundWorker按预期发送消息,并允许程序在任何时候正常运行。我有在按钮处理程序中发送消息的代码。现在我该把这个等价的代码放哪儿呢?我希望所有这一切仍由按钮按下处理。这是合适的处理程序吗?backgroundWorker1.RunWorkerAsync();在以下方面:private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {}我要把我的代码放到按钮处理程序中?在此之前:carga.progressBar1.Minimum = 0;carga.progressBar1.Maximum = 100;Carga是我使用ProgressBar的另一种形式。在这种情况下,我如何使用背景工作器?
查看完整描述

2 回答

?
神不在的星期二

TA贡献1963条经验 获得超6个赞

我知道这有点老了,但是如果另一个初学者正在经历这种情况,我将分享一些代码,这些代码将涵盖更多的基本操作,这里还有另一个示例,它还包括取消进程并向用户报告进程状态的选项。我将在上面的解决方案中添加Alex Aza给出的代码

public Form1(){
    InitializeComponent();

    backgroundWorker1.DoWork += backgroundWorker1_DoWork;
    backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
    backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;  
    //Tell the user how the process went
    backgroundWorker1.WorkerReportsProgress = true;
    backgroundWorker1.WorkerSupportsCancellation = true; //Allow for the process to be cancelled}
    //Start Processprivate void button1_Click(object sender, EventArgs e){
    backgroundWorker1.RunWorkerAsync();}//Cancel Processprivate void button2_Click(object sender, EventArgs e){
    //Check if background worker is doing anything and send a cancellation if it is
    if (backgroundWorker1.IsBusy)
    {
        backgroundWorker1.CancelAsync();
    }}private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e){
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(1000);
        backgroundWorker1.ReportProgress(i);

        //Check if there is a request to cancel the process
        if (backgroundWorker1.CancellationPending)
        {
            e.Cancel = true;
            backgroundWorker1.ReportProgress(0);
            return;
        }
    }
    //If the process exits the loop, ensure that progress is set to 100%
    //Remember in the loop we set i < 100 so in theory the process will complete at 99%
    backgroundWorker1.ReportProgress(100);}private void backgroundWorker1_ProgressChanged(object sender, 
    System.ComponentModel.ProgressChangedEventArgs e){
    progressBar1.Value = e.ProgressPercentage;}private void backgroundWorker1_RunWorkerCompleted(object sender, 
    System.ComponentModel.RunWorkerCompletedEventArgs e){
    if (e.Cancelled)
    {
         lblStatus.Text = "Process was cancelled";
    }
    else if (e.Error != null)
    {
         lblStatus.Text = "There was an error running the process. The thread aborted";
    }
    else
    {
       lblStatus.Text = "Process was completed";
    }}


查看完整回答
反对 回复 2019-07-06
  • 2 回答
  • 0 关注
  • 329 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信