Skip to content

Commit

Permalink
Rearragned thread dispatcher stopping internals to prevent disposal o…
Browse files Browse the repository at this point in the history
…f collections prior to thread completion.
  • Loading branch information
DJGosnell committed Nov 7, 2022
1 parent 09fcc5f commit 21b4eec
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -169,13 +169,26 @@ void Wrapper(Action obj)
var dispatcher = new ThreadDispatcher(1) { DispatcherExecutionWrapper = Wrapper };
dispatcher.Start();

await Task.Delay(500);

// Dummy action.
await dispatcher.Queue(() => { });

Assert.AreEqual(1, wrapperCallCount);
}

[Test]
public async Task DispatcherStopsWhenRunningLongRunningTasks()
{
var dispatcher = new ThreadDispatcher(1);
dispatcher.Start();

// Dummy action.
for (int i = 0; i < 10; i++)
{
dispatcher.QueueFireForget(_ => { Thread.Sleep(250); });
}

Assert.IsTrue(dispatcher.Stop(400));
}


}
2 changes: 1 addition & 1 deletion src/DtronixCommon/DtronixCommon.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<PropertyGroup>
<TargetFrameworks>net5.0;net6.0</TargetFrameworks>
<ImplicitUsings>enable</ImplicitUsings>
<Version>0.6.5.0</Version>
<Version>0.6.6.0</Version>
<Nullable>enable</Nullable>
<LangVersion>10</LangVersion>
<Company>Dtronix</Company>
Expand Down
14 changes: 7 additions & 7 deletions src/DtronixCommon/Threading/Dispatcher/ThreadDispatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -171,16 +171,11 @@ public bool Stop(int timeout = 1000)
for (int i = 0; i < _configs.ThreadCount; i++)
_queues[0].TryAdd(new StopLoop());


_cancellationTokenSource?.Cancel();

// Stop adding any items.
foreach (var queue in _queues)
{
queue.CompleteAdding();
queue.Dispose();
}

_queues = null;

var stopSuccessful = true;
// Join all the threads back to ensure they are complete.
Expand All @@ -190,7 +185,12 @@ public bool Stop(int timeout = 1000)
if (!thread.Join(timeout))
stopSuccessful = false;
}


// Dispose of all the queues since the threads have now been stopped.
foreach (var queue in _queues)
queue.Dispose();

_queues = null;
Threads = null;

return stopSuccessful;
Expand Down

0 comments on commit 21b4eec

Please sign in to comment.