【问题标题】:Print Number of Message per Second每秒打印消息数
【发布时间】:2021-11-19 09:18:54
【问题描述】:

我有一个无限的 while 循环。我想每秒打印一些消息。它应该每秒钟打印一次消息的计数。例如,如果我在 1 秒内有 500 条消息,那么它应该在消息之后将计数打印为 500,然后如果在接下来的 1 秒内它是 500,那么它应该在消息之后再次打印 500 这是我的代码:

static void SimulatePublish()
{
  var counter = 1;
  while (true)
  {
    counter++;
    var testMessage = new MqttApplicationMessageBuilder()
      .WithTopic("MqttData")
      .WithPayload($"Payload: This is my Code")
      .WithAtMostOnceQoS()
      .WithRetainFlag()
      .Build();
    if (_client.IsConnected)
    {
      Console.WriteLine($"publishing at {DateTime.UtcNow}");
      _client.PublishAsync(testMessage);
    }
  }
}

【问题讨论】:

  • 您好,它应该每秒打印一次消息数。例如,如果我在 1 秒内有 500 条消息,那么它应该显示计数为 500,然后如果在接下来的 1 秒内它是 500,那么它应该在消息之后再次打印 500
  • edit 原始问题,而不是在 cmets 中添加详细信息。此外,您需要展示您尝试过的内容以及它如何不起作用。你不能只是陈述一个要求并期望 SO 为你编写代码,那样做是行不通的。

标签: c# timer mqtt


【解决方案1】:
int messagesDiff = 0;
long startTime = DateTimeOffset.Now.ToUnixTimeSeconds(), timeDiff;

TimerCallback printingLambda = (o) =>
{
    timeDiff = DateTimeOffset.Now.ToUnixTimeSeconds() - startTime;
    Console.WriteLine("Messages per second: " + messagesDiff / (double)timeDiff);
    startTime = DateTimeOffset.Now.ToUnixTimeSeconds();
    messagesDiff = 0;
};

Timer timer = new Timer(printingLambda, null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));

while (true)
{
    //public message
    messagesDiff++;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-09
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 2016-07-03
    • 2015-08-30
    • 2019-11-03
    • 1970-01-01
    相关资源
    最近更新 更多