BackgroundWorker thread to Update WinForms UI

前端 未结 2 1293
星月不相逢
星月不相逢 2021-01-22 20:24

I am trying to update a label from a BackgroundWorker thread that calls a method from another class outside the Form. So I basically want to do this:

MainForm.co         


        
2条回答
  •  轮回少年
    2021-01-22 21:08

    You should use the ProgressChanged-Event to update the UI. The code for the BackgroundWorker should look something like:

    internal static void RunWorker()
    {
        int speed = 100;
        BackgroundWorker clickThread = new BackgroundWorker
        {
            WorkerReportsProgress = true
        };
        clickThread.DoWork += ClickThreadOnDoWork;
        clickThread.ProgressChanged += ClickThreadOnProgressChanged;
        clickThread.RunWorkerAsync(speed);
    
    }
    
    private static void ClickThreadOnProgressChanged(object sender, ProgressChangedEventArgs e)
    {
    
        someLabel.Text = (string) e.UserState;
    
    }
    
    private static void ClickThreadOnDoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = (BackgroundWorker)sender;
        int speed = (int) e.Argument;
    
        while (!worker.CancellationPending)
        {
            Thread.Sleep(speed);
            Mouse.DoMouseClick();
            Counter++;
            worker.ReportProgress(0, "newText-Parameter");
        }
    }
    

    }

提交回复
热议问题