Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm progress callback

Tags:

c#

callback

wpf

I have to implement very complex algorithm with a lot of iterations, matrix operations etc. There are two major loops for Fourier series approximation. I would like to know what is the best approach to implement progress callback. I na future I would like to use this algorithm in WPF app and I would like to implement progress bar. How to prepare algorithm to make progress bar implementaion easy in a future?

I am thinking about something like this:

static void Main(string[] args)
{
    Console.Write("Progres...  ");
    Alg((i) => UpdateProgress(i));            
}

public static void UpdateProgress(int iteration)
{
    string anim = @"|/-\-";            
    Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
    Console.Write(anim[iteration%5]);                        
}

public static void Alg(Action<int> progressCallback)
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(50);
        progressCallback(i);
    }
}
like image 582
Łukasz Adamus Avatar asked Feb 03 '26 12:02

Łukasz Adamus


1 Answers

If you prefer to use TPL, why not stick with it? You can use 'IProgress' http://msdn.microsoft.com/pl-pl/library/hh193692.aspx .

class Program
{
    static void Main(string[] args)
    {
        Console.Write("Progres...  ");

        Progress<int> progress = new Progress<int>();

        var task = Alg(progress);            

        progress.ProgressChanged += (s, i) => { UpdateProgress(i); };

        task.Start();
        task.Wait();
    }

    public static void UpdateProgress(int iteration)
    {
        string anim = @"|/-\-";
        Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
        Console.Write(anim[iteration % anim.Count()]);
    }

    public static Task Alg(IProgress<int> progress)
    {
        Task t = new Task
        (
            () =>
            {
                for (int i = 0; i < 100; i++)
                {
                    Thread.Sleep(50);
                    ((IProgress<int>)progress).Report(i);
                }
            }
        );
        return t;
    }
}
like image 79
semeai Avatar answered Feb 05 '26 00:02

semeai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!