Method returning progress of loop

1k views Asked by At

I'm creating a class library with a method, for example, OnetoTen(), which basically is a for loop counting from 1 to 10. What i'm trying to achieve is to call this method from another program and have it output what number/iteration the for loop is currently at.

Is the use of delegates/events the right way to go?

1

There are 1 answers

2
Andrew Radford On BEST ANSWER

You could use a callback (delegate) or an event.

Example using callback:

class Program
{
    static void Main(string[] args)
    {
        var counter = new Counter();

        counter.CountUsingCallback(WriteProgress);

        Console.ReadKey();
    }

    private static void WriteProgress(int progress, int total){
        Console.WriteLine("Progress {0}/{1}", progress, total);
    }
}

public class Counter
{
    public void CountUsingCallback(Action<int, int> callback)
    {
        for (int i = 0; i < 10; i++)
        {
            System.Threading.Thread.Sleep(1000);
            callback(i + 1, 10);
        }
    }

}

Example using event:

class Program
{
    static void Main(string[] args)
    {
        var counter = new Counter();
        counter.ProgessTick += WriteProgress;

        counter.CountUsingEvent();

        Console.ReadKey();
    }

    private static void WriteProgress(int progress, int total){
        Console.WriteLine("Progress {0}/{1}", progress, total);
    }
}

public class Counter
{
    public event Action<int, int> ProgessTick;

    public void CountUsingEvent()
    {
        for (int i = 0; i < 10; i++)
        {
            System.Threading.Thread.Sleep(1000);
            if (ProgessTick != null)
                ProgessTick(i + 1, 10);
        }
    }

}