c# - 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()
}
解决方案
您可以在收到消息时将 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;
}
推荐阅读
- python - 在 azure datafactory 中运行 python 脚本,使用 MSI 调用 API
- memory - 如果数量匹配,为什么我的 pod 不满足资源配额限制?
- python - 在 Cygwin 的 Python 中,os.symlink 没有创建正确的符号链接
- text - 文本摘要中的通用域和特定域有什么区别?
- c - C:有什么办法可以防止重复打开一个文件?
- python - 如何在python中使用opencv读取图像的掩码
- python - 在 python 3.7 中使用 Beautifulsoup 从 WSJ 抓取文章?
- django - ERR_CONNECTION_REFUSED 与 Django 和 Vue.js 捆绑文件
- java - 如何在 Spring Boot 中将多个域添加到 Access-Control-Allow-Origin?
- spring-boot - 弹簧靴 2 | 在接口中定义@RequestMapping