C#,如果计时器的当前时间大于

时间:2018-09-16 09:00:32

标签: c# timer stream grpc ienumerator

我正在接收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()
                }

1 个答案:

答案 0 :(得分:0)

只要收到消息,就可以将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;
                }