c# - C# Timer 将 null 传递给 Elapsed 事件处理程序的源参数
问题描述
每当我尝试运行这个 c# 计时器时,应用程序都会出错,说“参数不能为空:对象源”,我的实现基于微软文档页面。值得注意的是,当事件同步时也会发生这种情况。
private void SetTimer()
{
// TODO set to actual week
WeeklyNotificationTimer = new System.Timers.Timer(30000);
// Hook up the Elapsed event for the timer.
WeeklyNotificationTimer.Elapsed += async (sender, e) => await OnTimerFinishedAsync(sender, e);
WeeklyNotificationTimer.Start();
WeeklyNotificationTimer.AutoReset = true;
WeeklyNotificationTimer.Enabled = true;
}
private async Task OnTimerFinishedAsync(Object source, ElapsedEventArgs e)
{
await RunWeeklyNotification();
}
WeeklyNotificationTimer 被声明为
private System.Timers.Timer WeeklyNotificationTimer;
任何帮助表示赞赏。
编辑:
这是完整的错误文本:
System.ArgumentNullException
HResult=0x80004003
Message=Value cannot be null.
Parameter name: source
Source=System.Linq
StackTrace:
at System.Linq.Enumerable.Contains[TSource](IEnumerable`1 source, TSource value, IEqualityComparer`1 comparer)
at System.Linq.Enumerable.Contains[TSource](IEnumerable`1 source, TSource value)
at Columbus.WeeklyNotificationHandler.<RunWeeklyNotification>d__13.MoveNext() in C:\Users\(user)\Source\Repos\InternalTools\(project)\WeeklyNotificationHandler.cs:line 81
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Columbus.WeeklyNotificationHandler.<OnTimerFinishedAsync>d__12.MoveNext() in C:\Users\(user)\Source\Repos\InternalTools\(project)\WeeklyNotificationHandler.cs:line 74
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Columbus.WeeklyNotificationHandler.<<SetTimer>b__11_0>d.MoveNext() in C:\Users\(user)\Source\Repos\InternalTools\(project)\WeeklyNotificationHandler.cs:line 66
第 81 行来自 RunWeeklyNotification:
if (SelfReportedUsers.Contains(conversationReference.User)) { continue; }
第 74 行是
await RunWeeklyNotification();
第 66 行是
WeeklyNotificationTimer.Elapsed += async (sender, e) => await OnTimerFinishedAsync(sender, e);
解决方案
您的 Timer 类看起来不错。
您可以使用调试器并查看第 81 行中哪些值为 null 吗?
每次经过的时间都在调用 RunWeeklyNotification() ,其中的值为空。
推荐阅读
- c - 如何让我的代码在 C 中重复相同的问题
- akka - 如何用虚拟时间测试 Akka 演员?
- telegram - 如何通过电报发送通过谷歌表格发布的图表
- javascript - Discord.js 如果功能问题
- java - Graphics2D 和 GUI:方法的 ArrayList、方法引用错误
- c# - 根据页面对模型进行不同的验证
- php - 在数组递归php中添加数据
- javascript - 应用程序运行一段时间后节点 cron 任务不工作(node-cron、cronr、timexe)
- swiftui - NavigationView 的子视图在变量发生变化时自动返回父视图
- javascript - 我怎样才能让 sweet2alert 不再显示消息?