简体   繁体   English

BackgroundWorker线程更新WinForms UI

[英]BackgroundWorker thread to Update WinForms UI

I am trying to update a label from a BackgroundWorker thread that calls a method from another class outside the Form. 我正在尝试从BackgroundWorker线程更新标签,该线程从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. 我已经研究过诸如使用BackgroundWorker的progressupdate函数,调用等之类的东西,但是它们似乎并不是我所需要的。

here is some more of my code: 这是我的一些代码:

the MainForm: 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. 我想我的代码有些过于复杂了:\\并且使自己陷入困境。

You should use the ProgressChanged -Event to update the UI. 您应该使用ProgressChanged -Event来更新UI。 The code for the BackgroundWorker should look something like: BackgroundWorker的代码应类似于:

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

} }

Try to invoke the method. 尝试调用该方法。

For Example:- 例如:-

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM