0

I inherited an application that uses a Background Worker. Through the course of the application, there are multiple functions assigned to and removed from DoWork (see below). Is there a property or a method that can be called to evaluate which methods are currently assigned to the DoWork function, or is this something that should be tracked by the application?

ex:

worker.DoWork += method1;

{ Run some code }

worker.DoWork -= method1;

worker.DoWork += method2;

{ Run some code }

worker.DoWork -= method2;
MatejMecka
  • 1,448
  • 2
  • 24
  • 37
LizP
  • 178
  • 2
  • 2
  • 9
  • 1
    It is very wonky code, impossible to guess why its author liked to do it this way. Throwing it away is the best you could do with it. – Hans Passant Jul 26 '18 at 22:03

2 Answers2

-1

You can write a custom event accessor. Of course since it's custom, you end up doing the tracking yourself, but here's how you can do it.

class MyClass
{
    protected readonly List<EventHandler> list = new List<EventHandler>();

    public event EventHandler DoWork
    {
        add
        {
            list.Add(value);
        }
        remove
        {
            list.Remove(value);
        }
    }

    public void RaiseDoWork()
    {
        var args = new EventArgs();
        foreach (var func in list)
        {
            func(this, args);
        }
    }

    public IEnumerable<EventHandler> GetDoWorkDelegates()
    {
        return list;
    }
}


public class Program
{
    public static void HandleDoWork(object sender, EventArgs e)
    {
        Console.WriteLine("Event fired.");
    }

    public static void Main()
    {
        var c = new MyClass();
        c.DoWork += HandleDoWork; 
        c.RaiseDoWork();

        foreach (var d in c.GetDoWorkDelegates())
        {
            Console.WriteLine("Method name was {0}.", d.Method.Name);
        }
    }
}

Output:

Event fired.
Method name was HandleDoWork.

Working example on DotNetFiddle

Note: More code is needed if you want the above to be thread-safe.

John Wu
  • 50,556
  • 8
  • 44
  • 80
-2

The entire purpose of using events, rather than just delegates, is that it specifically prevents any code external to the type from doing anything other than adding or removing a handler. You can neither invoke, nor inspect, all of the handlers added to the event.

Servy
  • 202,030
  • 26
  • 332
  • 449