I have a class that exposes cancellable events according to the convention of raising an event before the state of the object changes and an event once the state is changed. The before-change event exposed by the publisher(server) is on the form StateChanging
and has as argument a CancelEventArgs
, while the after-change event is on the form StateChanged
. This provides the subscriber(client) of the event with the capability to cancel the operation before it starts.
Now I've changed one of these operations making it a long-running operation and I would like to give the subscriber the possibility to cancel the operation also after it has begun (and also to know the operation progress). I thought to the event-based asynchronous pattern.
The problem is that I would like to keep the before-change and after-change event pattern since it's the publisher that at some point requires the operation, while in the asynchronous pattern it seems to me that it is the client that specifically ask a certain operation to be run asynhronously. Another possibility (but does not seem elegant to me) might be to have the server exposing an event (e.g. OperationRequired
) that allow the client to know what needs to be accomplished on the server side and to call accordingly a RunOperationAsync()
method. Please comment and add your suggestions.
The Event-based Asynchronous Pattern is generally preferred for operations that are controlled by a UI. The alternative, the Asynchronous Programming Model, is generally preferred for server or library APIs. If you've chosen to implement the EAP, that's fine.
Take a look at the BackgroundWorker implementation - it is the best example of the EAP that supports cancellation, among other things. It offers cancellation via the standard CancelAsync()
method.