3

I have a delegate:

private delegate void ActivitySteps(string inputFolder, string outputFolder);

In one of the methods in my class I register various activities to it :

this.activitySteps = A;
this.activitySteps += B;

and so on...

Finally I invoke it :

this.activitySteps.Invoke(inputFolder, outputFolder);

Now I want to add logging so that I know which of the event i.e. method failed while invoking the delegate. (A or B or some other). Is there a way I could do that so that I don't have to log in each method and could centralize the logging within delegate.

Brendan Green
  • 11,676
  • 5
  • 44
  • 76
Amber
  • 1,229
  • 9
  • 29
  • Where are you actually having problems? Knowing how to create a log or adding to that log? You would just either create a new logger in each delegate or pass one in if you are writing to a single log. – Dispersia Apr 05 '16 at 22:13
  • I want to add logging information at one place while invoking the delegate so that I don't have to replicate the logging in all the methods. – Amber Apr 05 '16 at 22:15
  • You might be interested in reading [this answer](http://stackoverflow.com/a/374549/284111). Continuing where it started I would suggest reworking your logic to not rely on delegates order. – Andrew Savinykh Apr 06 '16 at 01:30
  • @Andrew Savinykh My Logic Doesn't depend upon the delegation order. I was just trying to get information that which step actually failed. – Amber Apr 11 '16 at 21:48

1 Answers1

3

You could use GetInvocationList() when invoking the delegates:

foreach( ActivitySteps del in this.activitySteps.GetInvocationList() )
{
    try
    {
        del.Invoke( inputFolder, outputFolder );
    }
    catch( Exception ex )
    {
        Console.WriteLine( "{0} threw {1}", del.Method.Name, ex );
    }
}
Kyle
  • 6,500
  • 2
  • 31
  • 41