Share a single resource (socket) between many objects, with async/await functionality

Unsure how to formulate my title, as my problem isn't one single issue.

What I've got, is a UdpClient object which I use to communicate with a device. This device accepts 1 request at a time, and after a while (a few seconds) it sends me back a response. During that wait time, it should not receive any other requests.

I have wrapped this UdpClient inside a "RequestReplyService"-class, which has a method "public byte[] SendRequest(byte[] request)", where the return-value is the response in the form of a byte array.

The RequestReplyService (single instance shared by all objects) will be injected to any object that needs to communicate with the device.

Will other objects automatically be blocked while SendRequest() is waiting during its UdpClient.Receive(), or do I need to use a lock inside SendRequest()?

In what order will the next calls to SendRequest() go, if multiple objects call it at "the same time", FIFO? And am I guaranteed that the correct return value is given to the correct caller?

How can I make this method async? Since it's an I/O bound task, it seems ideal (and not heavy I/O, just long response time)

I just don't have total grasp on async and thread safety. Here is a simplified version of my method.

public byte[] SendRequest(byte[] request) { // Send response and read the response. _client.Send(request, request.Length); return client.Receive(); // This may take a while } 

Should I have a lock around the send and receive calls, to ensure that no new requests are sent before a response for the previous request has been received? If so, how do I manage to use the UdpClient.ReceiveAsync()? (cannot use await inside lock).

Hope my point comes across. Thanks

by Sweetpipe via /r/csharp

Leave a Reply