Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
831 views
in Technique[技术] by (71.8m points)

c# - 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. 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...