Skip to content

Commit

Permalink
Use CancellationSource to properly dispose of threads in PrioritySche…
Browse files Browse the repository at this point in the history
…duler (#197)

* Use CancellationSource to properly dispose of threads in PriorityScheduler

* formatting
  • Loading branch information
adamhathcock authored Jan 3, 2025
1 parent 1fe1a54 commit 11fe8e8
Showing 1 changed file with 27 additions and 3 deletions.
30 changes: 27 additions & 3 deletions src/Speckle.Sdk/Serialisation/V2/Send/PriorityScheduler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,17 @@ namespace Speckle.Sdk.Serialisation.V2.Send;

public sealed class PriorityScheduler(ThreadPriority priority, int maximumConcurrencyLevel) : TaskScheduler, IDisposable
{
private readonly CancellationTokenSource _cancellationTokenSource = new();
private readonly BlockingCollection<Task> _tasks = new();
private Thread[]? _threads;

public void Dispose() => _tasks.Dispose();
public void Dispose()
{
_tasks.CompleteAdding();
_cancellationTokenSource.Cancel();
_tasks.Dispose();
_cancellationTokenSource.Dispose();
}

public override int MaximumConcurrencyLevel => maximumConcurrencyLevel;

Expand All @@ -24,9 +31,26 @@ protected override void QueueTask(Task task)
{
_threads[i] = new Thread(() =>
{
foreach (Task t in _tasks.GetConsumingEnumerable())
try
{
foreach (Task t in _tasks.GetConsumingEnumerable(_cancellationTokenSource.Token))
{
if (_cancellationTokenSource.IsCancellationRequested)
{
break;
}
TryExecuteTask(t);
if (_cancellationTokenSource.IsCancellationRequested)
{
break;
}
}
}
#pragma warning disable CA1031
catch (Exception)
#pragma warning restore CA1031
{
TryExecuteTask(t);
// ignored
}
})
{
Expand Down

0 comments on commit 11fe8e8

Please sign in to comment.