算法进程回调 [英] Algorithm progress 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);
}
}
推荐答案
你更喜欢使用 TPL
,为什么不坚持呢?
您可以使用IProgress http://msdn.microsoft.com /pl-pl/library/hh193692.aspx 。
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;
}
}
这篇关于算法进程回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!