State Machine Question
There is a State Machine with two Transitions in the same function.
static readonly object _object = new object();
lock (_object)
{
// I want Host received the event of SMTrans01 first .
Obj.StateMachine.Send((int)MyStateMachine.EventType.SMTrans01, new object[2] { Obj, MyStateMachine.EventType.SMTrans01 });
}
lock (_object)
{
// And then I want Host received the event of SMTrans02.
Obj.StateMachine.Send((int)MyStateMachine.EventType.SMTrans02, new object[2] { Obj, MyStateMachine.EventType.SMTrans02 });
}
I implemented my state machine code as above. I am not sure I understand Lock
statement correctly or not?
I need the events followed the the right order (Host received SMTrans01 first, and then host received SMTrans02 event).
After testing I found sometime host will receive the SMTrans02 event first. Looks like Lock
statement not work. I don't开发者_如何学Go know why.
Are there any good methods to approach it?
It looks like your problem has nothing to do with threads and locking.
I suspect that your Send method is asynchronous. The solution is to use a synchronous approach instead. Do not send the second event until you get an acknowledgement that the first event has been handled.
Alternatively, rewrite your receiving code so that it can handle the events coming out of order.
If you provide the code for Send
and describe more how your method is being called that would help debugging the problem.
if the order matters
EventType _state = EventType.SMTrans02;
if(_state == EventType.SMTrans02 )
{
_state =EventType.SMTrans01;
Obj.StateMachine.Send((int)_state, new object[2] { Obj, _state });
}
else
{
_state = EventType.SMTrans02;
Obj.StateMachine.Send((int)_state, new object[2] { Obj, _state });
}
for more complex situation you may use switch block or even use State Pattern
you need Lock only to sync the threads which may call those events.
精彩评论