'Receiving messages with checking if message is handled and checking timeout c#

I am asking for advice to create efficient algorithm for receiving message, checking timeout and doing appropriate action to time-outed situation (or simply throw an exception when timeout will occur).

I would like to create download process from the remote device. The app sends message to the remote device requesting element with specific ID. Then, the app starts waiting for this item and counts timeout. If it is timeout, the app should send request again. If app received requested item, saves it to the list, then should ask for another one (last ID+1).

I have HandleMessage method with message class in the input parameter. When user presses the button for download, the app starts task with requesting loop.

public class Message
{
   public int Id { get; set; }
   ...
}



private Message wantedMessage;
public void HandleMessage(Message msg)
{
   switch(msg.Id)
   {
      case 1: DoActionForFirst(); break;
      case 2: DoActionForSecond(); break;
      ...
      case IdForItemMessage: wantedMessage = msg; break;
   }
}

public void Download()
{
   for (int i = 0; i < requestedItemCount; i++)
   {
      SendRequestForMessage(i);
      Stopwatch stopwatch = Stopwatch.StartNew();

      while (true)
      {
         if (stopwatch.Elapsed >= TIMEOUT)
            throw new TimeoutException();

         if (wantedMessage != null)
         {
            AddItemToList(wantedMessage);
            wantedMessage = null;
         }
      }
   }
}

How will you attempt to resolve this problem? There are problems with:

  • check if wantedMessage is already handled or not;
  • While loop with statement true


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source