Skip to content

Commit 968df8b

Browse files
authored
Catch an exception from a timer's callback, because it can crash the entire application (#866)
1 parent f143f2e commit 968df8b

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

Source/EasyNetQ/Internals/Timers.cs

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
using System;
22
using System.Threading;
3+
using EasyNetQ.Logging;
34

45
namespace EasyNetQ.Internals
56
{
67
//https://stackoverflow.com/questions/4962172/why-does-a-system-timers-timer-survive-gc-but-not-system-threading-timer
78
public static class Timers
89
{
10+
private static readonly ILog logger = LogProvider.GetLogger(typeof(Timers));
11+
912
public static IDisposable Start(TimerCallback callback, TimeSpan dueTime, TimeSpan period)
1013
{
1114
var callbackLock = new object();
@@ -16,6 +19,10 @@ public static IDisposable Start(TimerCallback callback, TimeSpan dueTime, TimeSp
1619
{
1720
callback.Invoke(state);
1821
}
22+
catch (Exception exception)
23+
{
24+
logger.Error(exception, string.Empty);
25+
}
1926
finally
2027
{
2128
Monitor.Exit(callbackLock);
@@ -30,7 +37,14 @@ public static void RunOnce(TimerCallback callback, TimeSpan dueTime)
3037
var timer = new Timer(state =>
3138
{
3239
((Timer) state).Dispose();
33-
callback(state);
40+
try
41+
{
42+
callback(state);
43+
}
44+
catch (Exception exception)
45+
{
46+
logger.Error(exception, string.Empty);
47+
}
3448
});
3549
timer.Change(dueTime, Timeout.InfiniteTimeSpan);
3650
}

0 commit comments

Comments
 (0)