-1

I have a c# program which calls the function, the callee function, does some processes within a for loop. Now i want, as soon as the iterations are completed in the for loop, the caller function should get notified about the same. I know i can write the Console.WriteLine statement in the callee function itself, but that's not what i want, because i might be using that function somewhere else as well, where i don't want to show any status to end user. Here's what i am currently doing:

Caller function.
public static void Main(string[] args)
{
    Program p = new Program();
    p.Callee();
    // here i want to use the notification as a status for end user.
}

public void Callee()
{
    for(int i=0; i<10; i++)
    {
        //here i need some mechanism which would notify the above caller function, once each iterations are completed. (whether success or failure).
    }
}
Abbas
  • 4,948
  • 31
  • 95
  • 161
  • There are so many ways of solving this problem that you'll need to provide additional information or constraints. – John V Mar 25 '22 at 04:07
  • @JohnV not sure what more information you need, can you share any one of them to solve this? – Abbas Mar 25 '22 at 04:29

1 Answers1

1

There are two basic approaches that could work in this case. Pass a data structure to Callee() that it can add notifications to, or pass a delegate to Callee() so that it can do something. This example does the second. Also, note how I moved Callee() into a separate class. While creating a new instance of Program is possible, that's not how the Main method is intended to work.

Here is a fiddle: https://dotnetfiddle.net/DDE6f8

using System;

public class Program
{
    public static void Main(string[] args)
    {
        Action<int> handleIterationComplete = 
          (int i) => Console.WriteLine($"Iteration {i} complete.");
        
        var p = new ProgramClass();
        p.Callee(handleIterationComplete);
    }
}

public class ProgramClass
{
    public void Callee(Action<int> iterationCompleteHandler)
    {
        for (int i=0; i<10; i++)
        {
            //do some work
            Console.WriteLine($"Doing Iteration {i}");

            //post a notification
            iterationCompleteHandler(i);
        }
    }
}

In this example Caller defined what action to take when an iteration completes. This would allow you to call Callee() from a different context and specify different behavior for the notification.

John V
  • 1,286
  • 9
  • 15
  • Just to be strict, the name `iterationCompleteHandler` should be `iterationCompleteCallback`. The handler part is the `(int i) => Console.WriteLine($"Iteration {i} complete.");`. – Enigmativity Mar 25 '22 at 06:04