I would like to hear opinions on the best way to handle asynchronous operations with the Command pattern. Say we have the following example:
public class MyCommand {
The problem is this: MyCommand does not know if MyReceiver.DoSomething () has asynchronous parts of the code. If I wanted to push MyCommand to the cancellation table after it was executed, I could not guarantee that its receiver action was completely completed, which makes it undefined to find out if MyCommand reached the state in which the capability was canceled or not.
I personally thought of the following solution:
- Implement some kind of state control in Command
- Include "BeginExecute" and "EndExecute" in Command
- Include events in MyReceiver and make the team subscribe to them (this seems smelly to me)
To wrap everything up, MyCommand will turn into:
public class MyCommand { public MyCommand(MyReceiver receiver) { _myReceiver = receiver; _myReceiver.DoSomethingFinished += () => this.EndExecute(); } public void BeginExecute() { this.EnterExecutionState(); _myReceiver.DoSomething(); } public void EndExecute() { this.LeaveExecutionState(); }
Now I have the means to make sure that the command receiver has completed any action and is ready to push it onto the cancel stack. However, for the spam case, every single Receiver class containing asynchronous operations really bothers me.
I have not found much about this topic on the Internet and would like to hear different approaches.
OBS: getting a command to manage all asynchronous code is not an option :).
source share