call to async method vs event

Viewed 4324

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 !

3 Answers
Related