Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call to async method vs event

I am developping a client library for a network application protocol.

Client code calls the library to init it and to connect to server. The client can of course send requests to the server, but the server can also send requests (Commands, called Cmd below) to the client.

The transport protocol is TCP/IP, so basically the client library connect to the server and make a call to an async method to retrieve the next request or response from the server in order to avoid I/O blocking while waiting for response/requests from the server.

That being said, I see two possible solutions (only using C# constructs and no specific third party framework) in the library to allow the client to receive requests from the server :

Either offer an event in the library such as

public EventHandler<ReceivedCmdEventArgs> event ReceivedCmd;

that the client would subscribe to, in order to get notidied of requests incoming from the server. Of course for this mechanism I will have to make an async loop in the client library to receive requests from the server and raise the event on Cmd reception.

Or the other solution would be to make such a method in the client library

public async Task<Cmd> GetNextCmdAsync()

that the client code would call in an async loop to receive the cmds.

Are these solutions kind of the same ? Is it better to fully use async/await constrcuts of C#5 and not rely on events anymore ? What are the differences ? Any recommendation, remark ?

Thanks !

like image 714
darkey Avatar asked Aug 20 '12 10:08

darkey


1 Answers

I think that the event-driven approach is better in your case.

In fact, you're talking about an observable/observer pattern. An unknown number of listeners/observers are waiting to do something if some command is received.

Async/await pattern wouldn't work as well as event-driven approach, because it'd be something like I expect one result in opposite to I'll do what you want whenever you report me that you received a command.

Conceptually talking, I prefer the event-driven approach because it fits better with the goal of your architecture.

Async/await pattern in C# 5 isn't designed for your case, but it's for when some code executes an async task and next code lines should be executed after the task has received a result.

like image 58
Matías Fidemraizer Avatar answered Oct 10 '22 15:10

Matías Fidemraizer