BackgroundWorker线程更新WinForms UI [英] BackgroundWorker thread to Update WinForms UI

查看:63
本文介绍了BackgroundWorker线程更新WinForms UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从BackgroundWorker线程更新标签,该线程从Form之外的另一个类调用方法.所以我基本上想这样做:

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();

,但标签是私有的.我已经研究过诸如使用BackgroundWorker的progressupdate函数,调用等之类的东西,但是它们似乎并不是我所需要的.

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.

这是我的更多代码:

MainForm:

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

该类/方法称为:

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.

推荐答案

您应该使用ProgressChanged -Event来更新UI. BackgroundWorker的代码应类似于:

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

}

这篇关于BackgroundWorker线程更新WinForms UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆