Skip to content

Locally copy queue to avoid holding lock while Actions execute. #14

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

omgpuppy
Copy link

@omgpuppy omgpuppy commented Jan 16, 2020

Minor optimization - don't hold lock while executing queued actions.

lock (_executionQueue)
{
queueCopy = new Queue<Action>(_executionQueue);
_executionQueue.Clear();
Copy link
Owner

Choose a reason for hiding this comment

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

What is the reason for clearing the queue here? Because it's being moved over to an entirely new queue? I get the idea but it seems a lot can go wrong here.

Copy link
Author

Choose a reason for hiding this comment

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

Can you say more about what could go wrong?

The copy-and-clear step is effectively the same as the previous while-not-empty-dequeue; we're just moving the Invoke step outside of the lock. The invariant from the original implementation should still be the same - that each action in _executionQueue when Update is called gets executed on the main thread and that those actions are no longer in the queue.

This just means background threads only wait for a queue to copy instead of arbitrarily expensive actions to execute. (Admittedly, if the actions are that expensive, they likely shouldn't be executing on the main thread, but that's a different issue).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants