private void Consume(object state)
{
var surroundingContext = Current;
try {
SetSynchronizationContext(this); // temporarily replace surrounding sync context with this context
// run pending actions until there are no more
do {
Action a;
_pending.TryDequeue(out a); // always succeeds, due to usage of _pendingCount
a.Invoke(); // if an enqueued action throws... well, that's very bad
} while (Interlocked.Decrement(ref _pendingCount) > 0); // stop consumption when something will think the queue was empty
} finally {
SetSynchronizationContext(surroundingContext); // restore surrounding sync context
}
}