0

我有一个分层的工人阶级,我正试图从中获取进度报告。我所拥有的看起来像这样:

public class Form1
{
    private void Start_Click()
    {
        Controller controller = new Controller();

        controller.RunProcess();
    }
}

public class Controller
{
    public void RunProcess()
    {
        Thread newThread = new Thread(new ThreadStart(DoEverything));
        newThread.Start();
    }

    private void DoEverything()
    {
        // Commencing operation...
        Class1 class1 = new Class1();

        class1.DoStuff();

        Class2 class2 = new Class2();

        class2.DoMoreStuff();
    }

}

public class Class1
{
    public void DoStuff()
    {
        // Doing stuff
        Thread.Sleep(1000);

        // Want to report progress here
    }
}

public class Class2
{
    public void DoMoreStuff()
    {
        // Doing more stuff
        Thread.Sleep(2000);

        // Want to report progress here as well
    }
}

我以前使用过 BackgroundWorker 类,但我认为我需要一些更自由的形式来完成这样的事情。我想我可以使用委托/事件解决方案,但我不确定如何在这里应用它。假设我在 Form1 上有一些标签或其他东西,我希望能够使用 class1 和 class2 的进度进行更新,那么最好的方法是什么?

4

3 回答 3

1

使用事件是最直接的解决方案。当您从主线程订阅事件时,处理程序应检查Control.IsInvokeRequired以了解它是否必须再次调用自身Invoke(...)以将消息传递给正确的线程。

于 2010-04-15T20:16:38.603 回答
1

约翰是对的。您想利用事件,为此您需要使用一个或多个委托。这可能会给你一些想法。

http://www.yoda.arachsys.com/csharp/threads/winforms.shtml

于 2010-04-15T20:25:13.403 回答
0

如果您不想在通知期间阻塞处理线程,您可以使用Control.BeginInvoke()fire & forget 行为。

为了减少调用次数并定期更新进度,您可能希望将不同操作的状态封装在类中。
这样,您可以将状态写入例如易失性字段 - 可能是另一个聚合状态类 - 并使用 GUI 线程上的计时器来重新读取状态并相应地刷新标签。

于 2010-04-15T20:51:14.023 回答