Reputation: 980
I'm trying to make an async
function (I'm not very good with async
in general!) and lets say I want it to do this:
async public string Count()
{
int x = 0;
for(x; x<100000; x++)
{
await Task.Delay(1);
}
return "I'm done";
}
I would like to catch that "x" and store it somewhere else, or bind it to a textbox representing progress eg. "x / 100000"
How can I do that?
Upvotes: 1
Views: 144
Reputation: 4835
You can create an object of Progress class and pass it to the Count()
method. The Progress class has an event handler which can be called every time the async task has some progress to report. The progress is reported by the OnReport method.
var progress = new Progress<int>(); // define your own type or use a builtin type
progress += (counter) => { //This will be called each time the async func calls Report.
//counter will have the reported value
}
await Count(progress);
Inside the Count
function
async public string Count(Progress<int> progress)
{
int x = 0;
for(x; x<100000; x++)
{
await Task.Delay(1);
progress.OnReport(x);
}
return "I'm done";
}
Upvotes: 2