0

I have this super exciting program it's a console application, and I want to add a progress bar, but I don't understand how to add an event that kicks off progress increment, and how to display it in the console itself

I hope to use this project for the progress bar itself: https://www.codeproject.com/Tips/5255878/A-Console-Progress-Bar-in-Csharp

class Program
{
    static void Main(string[] args)
    {
           Executer ex = new Executer();
           ex.Execute();
           //print progress bar here?
     }
}

public class Executer 
{
    public static int progress = 0

    public void Execute()
    {
           Parallel.For(1, 100, i, => {
                  DoSomething();
                  //progress++ event?
           });
     }

     private void IncrementProgress()
     {
          Interlocked.Increment(ref progress);
     }
}
Yogi_Bear
  • 512
  • 2
  • 10
  • 24
  • 1
    [How to add an event to a class](https://stackoverflow.com/questions/85137/how-to-add-an-event-to-a-class) – John Wu Nov 27 '22 at 07:59

1 Answers1

1

Assign an event handler before executing

static void Main(string[] args)
    {
        var ex = new Executer();
        ex.AweSome += Console.WriteLine;
        ex.Execute();

        ex.AweSome -= Console.WriteLine;
    }

public class Executer
{
    public delegate void MyEventHandler(int count);
    public event MyEventHandler? AweSome;

    public void Execute()
    {
        var progress = 0;
        var countLock = new object();

        Parallel.For(1, 1000, (_) =>
        {
            DoSomething();
            lock (countLock)
            {
                IncrementProgress(progress++, AweSome);
            }
        });
    }

    private static void IncrementProgress(int progress, MyEventHandler? eventHandler)
    {
        eventHandler?.Invoke(progress);
    }
}

Don't forget to unsubscribe after using the delegate. I also assume that the DoSomething() method is thread-safe

Viachaslau S
  • 106
  • 1
  • 5