I am writing (trying) a client server application with these 3 layers:
- Client and Server wrapper classes for TcpClient and TcpServer, handling connection, multi-threading and NetworkStream read/block/write routines.
- Business logic BizClient and BizServer which implements Protocol and expose only “FetchDataFromServer()” kind of methods which hides underlying Protocol.
- Application and UI level. This level wraps BizClient and BizServer to run as Windows Services, Console apps or WinForms applications.
Now I am on the way to implement support for async calls on layer 1 upwards. Async calls in the .NET style typically involves an object state so that callback can know from where it should continue.
In the end on each layer from 3 to 1 to the .NET framework, I have to encapsulate the object state from the upper layer, add current layer’s state and then pass to next lower layer. This means writing a different struct on each layer and it looks cumbersome.
struct State
{
object bizState; // cannot know higher layer state type at lower layers
object muchInfo;
}
struct BizState
{
object appState;
object muchInfo;
}
struct AppState
{
object muchInfo;
}
Is there a better and quick way to do it rather than writing structs to wrap the states?
Well, technically: no; However, there are many workarounds to this problem. Consider using a generic state object (dump structures), which can have an InnerState (Just like an Exception). you can also choose to not to focus on state objects to much (they were mostly used during the earlier periods of .NET when we didnt have lambda’s and anonymous methods) and rely on closures instead.Lastly you can skip Event based Async and lean on TPL.