通过检查是否处理消息并检查超时C#,接收消息

发布于 2025-01-29 11:02:37 字数 1106 浏览 4 评论 0原文

我要求提供建议,以创建有效的算法,以接收消息,检查超时并对超时情况采取适当的措施(或在发生超时时简单地引发例外)。

我想从远程设备创建下载过程。该应用将消息发送到带有特定ID的远程设备请求元素。然后,该应用开始等待此项目并计算超时。如果是超时,则应用程序应再次发送请求。如果已收到所请求的项目,将其保存到列表中,则应要求另一个(最后一个ID+1)。

我在输入参数中具有带有消息类的handlemessage方法。当用户按按下下载按钮时,应用程序从请求循环开始任务。

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;
         }
      }
   }
}

您将如何尝试解决此问题? 存在问题:

  • 检查是否已经处理了通缉犯;
  • 而循环与语句true

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文