首页 > 解决方案 > 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);

标签: c#timer

解决方案


您的 Timer 类看起来不错。

您可以使用调试器并查看第 81 行中哪些值为 null 吗?

每次经过的时间都在调用 RunWeeklyNotification() ,其中的值为空。


推荐阅读