Skip to content

Fix consumer loop #772

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 25, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -40,25 +40,27 @@ public void StopWork()
class WorkPool
{
readonly ConcurrentQueue<Action> _actions;
readonly SemaphoreSlim _semaphore = new SemaphoreSlim(0);
readonly CancellationTokenSource _tokenSource;
CancellationTokenRegistration _tokenRegistration;
volatile TaskCompletionSource<bool> _syncSource = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
private Task _worker;

public WorkPool()
{
_actions = new ConcurrentQueue<Action>();
_tokenSource = new CancellationTokenSource();
_tokenRegistration = _tokenSource.Token.Register(() => _syncSource.TrySetCanceled());
}

public void Start()
{
_worker = Task.Run(Loop);
_worker = Task.Run(Loop, CancellationToken.None);
}

public void Enqueue(Action action)
{
_actions.Enqueue(action);
_semaphore.Release();
_syncSource.TrySetResult(true);
}

async Task Loop()
Expand All @@ -67,30 +69,32 @@ async Task Loop()
{
try
{
await _semaphore.WaitAsync(_tokenSource.Token).ConfigureAwait(false);
await _syncSource.Task.ConfigureAwait(false);
_syncSource = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
}
catch (TaskCanceledException)
{
// Swallowing the task cancellation exception for the semaphore in case we are stopping.
}

if (!_tokenSource.IsCancellationRequested && _actions.TryDequeue(out Action action))
while (_tokenSource.IsCancellationRequested == false && _actions.TryDequeue(out Action action))
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice catch. That's what happens when I code late hours...

{
try
{
action();
}
catch (Exception)
{
// ignored
}
}

}
}

public void Stop()
{
_tokenSource.Cancel();
_tokenRegistration.Dispose();
}
}
}
Expand Down