更新GUI多线程应用程序

更新GUI多线程应用程序

本文介绍了更新GUI多线程应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有主程序

static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Worker w1 = new Worker(1);
        Worker w2 = new Worker(2);
        Thread w1Thread = new Thread(new ThreadStart(w1.StartWorking));
        Thread w2Thread = new Thread(new ThreadStart(w2.StartWorking));
        w1Thread.Start();
        w2Thread.Start();
        Application.Run(new MainWindow());
        if (w1Thread.IsAlive)
        {
            w1Thread.Abort();
        }
        if (w2Thread.IsAlive)
        {
            w2Thread.Abort();
        }
    }
}

和工人阶级:

class Worker
{
    public int m_workerId;
    public bool m_workerLifeBit;
    public bool m_workerWork;

    public Worker(int id)
    {
        m_workerId = id;
        m_workerLifeBit = false;
    }
    public void StartWorking()
    {
        while (!m_workerWork)
        {
            m_workerLifeBit = false;
            System.Threading.Thread.Sleep(5000);
            m_workerLifeBit = true;
            System.Threading.Thread.Sleep(5000);
        }
    }
}

我在MainWindow表格上有checkBox.如何监视Worker变量m_workerLifeBit的状态并在MainWindow checkBox中显示其更改?

I have checkBox on MainWindow form.How to monitor state of Worker variable m_workerLifeBit and display its changes in MainWindow checkBox?

我找到了这个问题与解答如何从C#中的另一个线程更新GUI?但是答案没有显示完整的示例,并且我使用线程安全委托失败.

I have found this q&a How to update the GUI from another thread in C#? hovewer the answer does not show complete example, and I failed with using thread safe delegate.

我想要一些事件机制,该事件机制可以在Worker.StartWorking中触发并以MainWindow形式捕获在插槽中.

I want some event mechanism that I fire in Worker.StartWorking and catch in slot in MainWindow form.

推荐答案

以下是使用事件:

class Worker
{
    public event Action<bool> WorkerLifeBitChanged;

    // ...

    public void StartWorking()
    {
        // ...

        m_workerLifeBit = false;
        OnWorkerLifeBitChanged();

    // ...

    private void OnWorkerLifeBitChanged()
    {
        if (WorkerLifeBitChanged != null)
            WorkerLifeBitChanged(m_workerLifeBit);
    }

然后您在Main中为事件进行连线:

Then you wire up the event in Main:

//...
var mainWindow = new MainWindow();

w1.WorkerLifeBitChanged += mainWindow.UpdateWorkerLifeBit;
w2.WorkerLifeBitChanged += mainWindow.UpdateWorkerLifeBit;

w1Thread.Start();
w2Thread.Start();

Application.Run(mainWindow);
//...

MainWindowMainWindow中的实现:

public void UpdateWorkerLifeBit(bool workerLifeBit)
{
    if (this.checkBox.InvokeRequired)
    {
        this.Invoke(new Action(() => checkBox.Checked = workerLifeBit));
    }
    else
    {
        checkBox.Checked = workerLifeBit;
    }
}

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

08-13 01:44