Should multi-threading be considered while using receiving data using Websocket

126 views Asked by At

I have to read the data from WebSocket URL ( Full Web socket endpoint is provided. i.e. 'wss://someURL/ws/websocket' ). The response is json based on information. In fact, these are events of IOT devices.

Example Response :

{
  "device_id": "ce95003e-a619-4992-bc47-e4473816158d",
  "id": "dae69be5-8da0-459c-af2f-683ca0f7e4a1",
  "timestamp": "2016-03-15T19:35:16.500014Z",
  "status": "running"
}

The device statuses could be running, repaired, errored, and idle. If the device status is errored, it will be repaired automatically and a repaired event will be sent before resetting it to idle again.

I am using the following code as of now to connect with WebSocket for receiving data.

ClientWebSocket webSocket = new ClientWebSocket();
    try
    {
        byte[] buffer = new byte[1024]; // storing data here, Could be Concurrent Queue ???

        await webSocket.ConnectAsync(new Uri("wss://someURL.io/ws/websocket"), CancellationToken.None);
        while (true)
        {
            WebSocketReceiveResult result = await webSocket.ReceiveAsync(buffer, CancellationToken.None);
            string data = Encoding.UTF8.GetString(buffer, 0, result.Count);
            Console.WriteLine(data);
        }
    }
    catch(Exception ex)
    {

    }

This data will be preserved later in the databases or in memory ( perhaps doesn't matter ). But the data needed to be exposed as JSON-based API for frontends to show.

Question: Do I need to handle multi-threading? In which context, data concurrent access must be implemented? Does the buffer need to be thread-safe ?

1

There are 1 answers

3
JonasH On

You very rarely need multi threading.

Using async/await works perfectly well in a single threaded context (i.e. a UI program).

If you are running it in a multi threaded context, like a console program, it can be a little more difficult. But you should be fine as long as you are awaiting any tasks as soon as possible. That should prevent more than one thread from running at any point in time, at least for your code.

Your specific example looks perfectly fine to me.

If you do use multi threaded code, i.e. something like Task.Run, you will need to ensure that your code is thread safe.