Algorithms for reporting the progress of asynchronous function calls
What sort of algorithms are used to compute the progress of a function call?
Obviously its easy to do if you have a loop, something like:
Action<Double> notifier = d => Console.WriteLine("Completed: " + d.ToString());
Double _interval = 0.05;
for (int i = 0; i < 1000; i++)
{
int rem = default(int);
Math.DivRem(i, _interval, out rem);
if (rem == 0)
{
double progress = (double)i / 1000;
notifier(progress);
}
}
But what about when you just have some generic delegate and you'd like to run it asynchronously but also notify another thread of its progress, and you can't gaurantee that you can straightforwardly use a for-loop? Some other straightforward ways might be:
1) Time the function first (very bad for performance though if its a long running task)
2) Store past timings of the function in a log and开发者_JAVA技巧 use that (but this doesnt necessarily take into account extra variables - cpu, memory, etc. at the specific time of the task)
However do any more advanced algorithms exist, even if only to approximate the progress?
The BackgroundWorker
class has an update callback, but in answer to your question of a 'generic algorithm' for finding completion, Not really. The closest you can get is estimating based on Function Length (http://www.ndepend.com/) which will get you length in lines of code.
Pass the worker function a callback delegate and have it report it's progress back to the UI.
The UI shouldn't be in charge of "figuring out what to do", instead it should just take updates from the worker.
For example:
void longRunningFunction(Action<int> updateCallback)
{
// Do something long, but on measurable places, call updateCallback
updateCallback(50);
}
And in the UI:
longRunningFunction(x => progressBar.SetProgress(x));
Is this an academic question?
If not, you could opt to use BackgroundWorker
, which has a built in ReportProgress
method
http://msdn.microsoft.com/en-us/library/ka89zff4.aspx
I suppose you could also use .net reflector to look at its implementation if you're curious
精彩评论