首页 > 解决方案 > c# 如果计时器的当前时间大于

问题描述

我正在接收一个 gRPC 响应流,如果 500 毫秒后没有收到消息,我想调用一个操作。我打算使用 Stopwatch 类,但它更多地用于调试,我担心它可能不是最有效的方法。我想在我现有的方法中做一些事情:

while (await streamingCall.ResponseStream.MoveNext(
                    default(CancellationToken)))
                {

                }

这样:

while (await streamingCall.ResponseStream.MoveNext(
                    default(CancellationToken)))
                {
                    //Message received
                    //Begin some sort of timer
                    //If no other message has been received for 500ms, execute ExampleMethod()
                }

标签: c#timerstreamgrpcienumerator

解决方案


您可以在收到消息时将 DateTime 分配给一个变量,并在 Timer 中从中减去旧时间,以查看自上一条消息以来经过了多少时间:

DateTime LastMsgTime = DateTime.MinValue;
Timer timer = new Timer { Interval = 50, Enabled = false };
timer.Tick += (s,e) => 
{ 
    if((DateTime.Now- LastMsgTime).TotalMilliSeconds > 500)  
       {ExampleMethod(); timer.Enabled = false; }
};
while (await streamingCall.ResponseStream.MoveNext(
                    default(CancellationToken)))
                {
                     LastMsgTime = DateTime.Now;
                    //Message received
                    timer.Enabled = true;
                }

推荐阅读