Yogi_Bear
Yogi_Bear

Reputation: 594

How to increment progressbar using event handler and parallel.for

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);
     }
}

Upvotes: 0

Views: 342

Answers (1)

Viachaslau S
Viachaslau S

Reputation: 126

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

Upvotes: 1

Related Questions