Algorithm progress callback

2019-07-17 20:01发布

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

标签: c# wpf callback
2条回答
ゆ 、 Hurt°
2楼-- · 2019-07-17 20:12

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;
    }
}
查看更多
混吃等死
3楼-- · 2019-07-17 20:25

You need object which implements interface INotifyPropertChanged. The property of this object that represents progress state will be bound to XAML element that visualize that progress state (Progressbar). In your algorithm you need just set this property to appropriate value. Your algorithm can get this object as parameter. Or you can set this property in delegate which is supplied to you algorithm. WPF takes care about delivering change of property to UI thread if you are working with multiple threads.

查看更多
登录 后发表回答