Reputation: 13
How can I report real-time progress of a method within a class?
public class Foo{
public string Bar(){
int i = 0;
while(true)
{
i++;
//return i.ToString();
if(i > 10) break;
}
return "Loop end";
}
}
Foo foo = new Foo();
public void ShowStatus()
{
string status = foo.Bar();
//change the string value to each while loop
}
In this case, the expected output would be to update the string to each loop without the method having to end.
Upvotes: 0
Views: 137
Reputation: 43429
You could add an event in your Foo
class:
public delegate void ProgressEventHandler(object sender, ProgressEventArgs e);
public event ProgressEventHandler Progress;
...and then subscribe to this event from your other class:
Foo foo = new Foo();
foo.Progress += (sender, e) => { /* Do something */ };
...but you'll need to write a lot of code, including the class ProgressEventArgs
, and going async with the Progress
generic class as suggested by @Stefan is probably easier.
Upvotes: 1
Reputation: 672
You could refactor your method to run asynchronously and pass an IProgress
object to it:
public async Task ShowStatusAsync(IProgress<StatusProgress> progress)
{
...
progress?.Report(new StatusProgress(...));
}
Here is some further information about that pattern: https://learn.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/task-based-asynchronous-pattern-tap
Upvotes: 3