Reputation: 1279
Let's say I need to implement a C# class library that executes a long-running calculation. When some of the values calculated inside the calculation cross a certain threshold, I have to notify the user, nothing more.
In this case, how do I implement events inside a task? Is that even a proper solution? If not, how can I notify the user of things happening inside my task?
Upvotes: 3
Views: 6763
Reputation: 1279
I've read and experimented more with the problem, and seeing that all I need is to run code on the UI thread when certain conditions of the task are met, it's better to go the IProgress route (Peter Bons and Servy's recommendation). Simpler, better and fully supported. The link posted by Peter Bons (authored by Stephen Cleary) is a great writeup on how to do it.
Thanks to everyone for the help.
Upvotes: 1
Reputation: 228
Depending on what you desire to have happen when you say "notify the user", there are quite a few options, some more complex than others (e.g. using a messaging library like RabbitMQ).
However, a simple answer to your question would interpret "notify the user" as meaning "notify the caller of my long running process." In that case, you could create an EventHandler in the class that has your async long running process, and simply call that event handler when you want to "notify" your caller.
Code for the class could look like this:
public class LongTask
{
public event EventHandler StillInProgress;
public async Task<bool> LongRunningProcessAsync()
{
await Task.Delay(5000);
OnStillInProgress(new EventArgs());
await Task.Delay(5000);
return true;
}
protected virtual void OnStillInProgress(EventArgs e)
{
StillInProgress?.Invoke(this, e);
}
}
In the code above, the caller of your long running process could also subscribe to your "StillInProgress" event, and get notifications whenever you call it.
Subscribing to event by caller would look something like this:
var longRun = new LongTask();
longRun.StillInProgress += LongRun_StillInProgress;
// Method that will handle the "notification"
private void LongRun_StillInProgress(object sender, EventArgs e)
{
Debug.WriteLine("InProgress");
}
There are other options, but this is perhaps the most straight-forward.
Upvotes: 3