开发者

Horrible "Callback chains" in winforms application

开发者 https://www.devze.com 2023-04-09 00:07 出处:网络
I\'m working on a winforms application that is very complicated, and has massive callback chains being passed around all over the place.

I'm working on a winforms application that is very complicated, and has massive callback chains being passed around all over the place.

As an example loosely based on this code, there could be a "Manager" class, that spawns a class "SetUpWorkerThreads" class, which creates a "HandleWorker" thread for say 10 workers. The worker thread needs to call back to the manager class on occasion, to achieve this the code looks like this:

public class Manager
{
    public delegate void SomethingHappenedHandler();

    private void Init()
    {
     开发者_StackOverflow   var x = new SetUpWorkerThreads(SomethingHappened);
    }

    private void SomethingHappened()
    {
        // Handle something happened
    }

}

public class SetUpWorkerThreads
{
    private readonly Manager.SomethingHappenedHandler _somethingHappened;

    public SetUpWorkerThreads(Manager.SomethingHappenedHandler somethingHappened)
    {
        _somethingHappened = somethingHappened;
    }

    public void SetupTheThreads()
    {
        // Contrived!
        for (int x=0; x<10; x++)
        {
            var worker = new Worker(_somethingHappened);
            new Thread(worker.DoingSomething).Start();
        }
    }
}

public class Worker
{
    private readonly Manager.SomethingHappenedHandler _somethingHappened;

    public Worker(Manager.SomethingHappenedHandler somethingHappened)
    {
        _somethingHappened = somethingHappened;
    }

    public void DoingSomething()
    {
        // ... Do Something
        _somethingHappened();
    }
}

In reality, there can be many more classes involved, each passing around a mass of callbacks for various things. I realise that poor class/application design is playing a part in this, but are there better ways to go about handling these interactions between classes, specifically in winforms apps, and when a lot of threading is going on?


I can't see that the threading makes it more or less problematic.
One alternative is to use events instead of callbacks, but that won't break up the long chains and will give you an unsubscribing hell too.

One possible approach is to create an object responsible for handling all the events. Either as a singleton or as a single object that you pass to all your threads (instead of the callbacks). Then you can have a simple interface on the EventRouter object to raise events from the threads. You can then subscribe to events on the EventRouter where you need to handle "something happened".

Edit
Something the GoF pattern Mediator but with a publisher-subscriber twist.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号