BackgroundWorker thread to Update WinForms UI

只谈情不闲聊 提交于 2019-12-20 03:40:17

问题


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.counterLabel.Text = Counter.ToString();

but the label is private. I have looked into things like using BackgroundWorker's progressupdate function, invoke, etc but they don't seem to be what I need.

here is some more of my code:

the MainForm:

clickThread.DoWork += (s, o) => { theClicker.Execute(speed); };
clickThread.RunWorkerAsync();

The Class/Method called:

public void Execute(int speed)
{
    while (running)
    {
       Thread.Sleep(speed);
       Mouse.DoMouseClick();
       Counter++;
       //Update UI here
    }
}

I think I have overly complicated my code a bit :\ and backed myself into a corner.


回答1:


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");
    }
}

}




回答2:


Try to invoke the method.

For Example:-

this.Invoke((Action)(() => Resources.xobjMF.Enabled = true));


来源:https://stackoverflow.com/questions/36591068/backgroundworker-thread-to-update-winforms-ui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!