Reputation: 5466
There are couple of methods in a class that perform some lengthy operation and should periodically report progress to the caller, e.g. to display on presentation layer, log in file, etc.
I've used following solution in the past, but I'm concerned if that is the preferred way to do it:
I have callback delegate defined like that:
public delegate bool ProgressCallback(double percentCompleted, object arg);
Then my "worker" method is like that:
public bool DoSomething(bool firstArg, int anotherArg, ProgressCallback progressCallback, object callbackArg);
I invoke progressCallback
after each iteration of a long process, and if it returns false, that means the operation should be aborted.
Note that the process has to be synchronous, there is no need for asynchronous implementation.
I just see repeating this technique over and over in my code, so I'm concerned whether this is a recommended pattern. Is this how you would implement such thing? Should I use events instead, or does such simple implementation seem ok for you?
Upvotes: 0
Views: 113
Reputation: 174309
I would use an event with a bool flag in the event arguments. This bool flag can be set by the consumer and functions as your abort signal.
Upvotes: 0
Reputation: 34013
That is the right way to do it!
But to save you some time (and code) probably, look at the BackgroundWorker
Upvotes: 1