Skip to content

Commit 04cbb02

Browse files
authored
Merge pull request #550 from dacky179/ThreadSafeScheduleExecution
Make TimerId of ScheduleExecution thread safe.
2 parents 4c8a3de + b6f5d0e commit 04cbb02

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

src/Moryx/Threading/ParallelOperations.cs

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -128,19 +128,24 @@ public int ScheduleExecution<T>(Action<T> operation, T userState, int delayMs, i
128128
/// </summary>
129129
public int ScheduleExecution<T>(Action<T> operation, T userState, int delayMs, int periodMs, bool criticalOperation) where T : class
130130
{
131-
var id = ++_lastTimerId;
131+
// thread safe increment of timer id
132+
int id = Interlocked.Increment(ref _lastTimerId);
133+
132134
var timer = new Timer(new NonStackingTimerCallback(state =>
133135
{
134136
try
135137
{
136138
operation((T)state);
137-
if (periodMs <= 0)
138-
StopExecution(id);
139139
}
140140
catch (Exception ex)
141141
{
142142
HandleException(ex, operation, criticalOperation);
143143
}
144+
finally
145+
{
146+
if (periodMs <= 0)
147+
StopExecution(id);
148+
}
144149
}), userState, delayMs, periodMs);
145150

146151
lock (_runningTimers)

0 commit comments

Comments
 (0)