C#计时器将null传递给Elapsed事件处理程序的源参数

时间:2019-06-18 13:42:04

标签: c# timer

每当我尝试运行此C#计时器时,应用程序都会出错,提示“参数不能为空:对象源”,我的实现基于Microsoft docs页面。值得注意的是,事件也是同步发生的。

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);

1 个答案:

答案 0 :(得分:0)

您的Timer类看起来不错。

您可以使用调试器在第81行上查看哪些值为空吗?

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