BackgroundWorker thread to Update WinForms UI

前端 未结 2 1209
星月不相逢
星月不相逢 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:04

    Try to invoke the method.

    For Example:-

    this.Invoke((Action)(() => Resources.xobjMF.Enabled = true));
    
    0 讨论(0)
  • 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");
        }
    }
    

    }

    0 讨论(0)
提交回复
热议问题