Share via


Introducing CommunicationState

It's hard to believe that I introduced the ICommunicationObject state machine six months ago but never got around to talking about the CommunicationState enumeration that actually describes the states. Let's fix that today. I'll specifically talk about our CommunicationObject implementation.

 public enum CommunicationState
{
   Created = 0,
   Opening = 1,
   Opened = 2,
   Closing = 3,
   Closed = 4,
   Faulted = 5,
}

There are six states in total for a CommunicationObject. Every object starts in the Created state and proceeds in a one-way progression through the Opening, Opened, Closing, and Closed states. Every object that's Opened gets there from having been Opening and every object that's Closed gets there from having been Closing. However, it's possible to jump from any of the previous states to Closing without going through the states in between. You can close an object without having ever opened it.

An object that's not in the process of being closed can be faulted to indicate that it is no longer valid. That means that an object that is Created, Opening, and Opened can be faulted, but not one that is Closing, Closed, or has already been faulted before. Once an object is Faulted, the only thing you can do with it is to close it.

There are only a small number of methods that actually modify the state.

The state is set to Created in the constructor of CommunicationObject.

The state is set to Opening when either BeginOpen or Open is called.

The state is set to Opened when OnOpened is called. This happens after calling OnOpening and OnOpen but before the Opened event occurs.

The state is set to Closing when BeginClose, Close, or Abort is called.

The state is set to Closed when OnClosed is called. This happens after calling OnClosing and OnClose but before the Closed event occurs.

And finally, the state is set to Faulted when Fault is called.

Next time: Using HTTP in System.Net