Chapter 15. Queues and Concurrency
Up to the previous chapter, every block of the workbench could remember its own things. But one question has been left until now: what happens when ten people arrive at once.
One handler function runs slowly, a second person clicks the same button — do both run, or does one wait for the other? Ten people click at the same time — do they line up in a queue, or are they rejected on the spot? What we are talking about here is behavior, not “performance optimization”. After the user clicks, what they actually see is “queuing”, “computing”, or “application busy”.
Without a queue, every click immediately starts an execution. Ten people clicking at once means ten running at once; the hundredth person clicking means a hundred. The server’s threads, memory, and downstream database connections cannot hold up under that. The job of a queue is to funnel this flood into one (or a few) controllable pipes. There is a fixed number of how many can run, and when too many are waiting, they get blocked.
How events are queued, how many can run at once, what happens when too many are waiting, and one place most likely to make all of the above fail together — the handler function is written badly.
The sample adds a thirteenth block to the workbench. The queue module: five slow tasks in two groups, one release button, one batch button. The slow tasks do not pretend to be slow with Thread.Sleep; they wait for a “release” instead, and the release is given by another event. So “exactly how many are running at the same time” is something you can read from the log, no guessing.
This design is how this chapter verifies things. You can also see concurrency with a fixed wait (say each task sleeps two seconds), but that experiment is unreliable — if the machine is busy for a moment within those two seconds, the conclusion changes. Waiting for a “release” is different. You decide when a task moves; whether it is really running at the same time depends only on whether the “entry” and “exit” times overlap.
15.1 Queue and Event Execution
By default, an application comes with a queue. You write no code for it. Every click, every submit first enters the queue, and the queue decides when it runs.
Figure 15-1 The path an event takes through the queue: entering, waiting, taken by group, executing
Figure 15-1 has three gates, each with its own job,
- Queue limit (
maxSize), how many events can be waiting at once; - Concurrency group (
concurrencyId). Bindings in the same group share one “how many run at once” limit; - Concurrency limit (
concurrencyLimit), what that limit actually is, as a number.
The three parameters are written at two levels. The queue limit and the default concurrency go on the application-level Queue(...); grouping and a single event’s concurrency go on the binding’s Click(...). Which level you write it at decides how wide a scope it controls.
The three are independent of each other. The queue limit governs “those waiting”, the concurrency limit governs “those running”. When one is full, it rejects; when the other is full, it waits — two completely different behaviors.
When the queue picks up a task it has to pass the concurrency group first. Each time it picks one from a group that “still has a free slot”, which group it picks and which item within the group are not guaranteed to follow arrival time. So do not count on “first in, first out”. Within the same group the earlier one runs first; between different groups there is no order. This detail explains why A’s second task keeps waiting while B, which arrived later, can run first.
Each event gets a number when it enters the queue, and the front end uses that number to ask “what position, how much longer”. rank is the position (0 means next), rank_eta is the estimated wait in seconds, queue_size is the total number waiting in the whole queue. The estimate is rough. It is computed as “how many ahead × average duration”, so a single unusually slow task throws it off.
The queue’s state can be queried. /gradio_api/queue/status returns a snapshot.
{"msg":"estimation","event_id":null,"rank":null,"queue_size":3,"rank_eta":null}
When two slow tasks are waiting and one is running in the sample, queue_size is 2. It is the number “waiting”, not counting the running one, and it never exceeds the queue limit. The queue counts this number itself.
There is another limit not shown in the figure. The whole queue runs at most 40 at once; that is the default, and the application can change it. On a standalone host you write Launch(maxThreads: 8); when you plug into an existing ASP.NET Core host with AddGradio, you write AddGradio(options => options.MaxThreads = 8). It is larger than any single group’s concurrency limit, so you rarely hit it; but the question “I set unlimited, why does it still run in batches” usually has its answer at this level.
40 is not a thread count. Tasks in the queue run asynchronously; one thread can carry several tasks (yielding while waiting on IO). What it limits is “how many jobs are in hand at once”. No matter how many concurrency limits you add up, they cannot exceed it. If you really need to loosen it, raise this number first, then check whether memory and downstream can take it; if you raise it past a hundred and still see queuing, think about multiple processes and multiple instances rather than adding more parameters.
The queue is on by default. To turn it off for one kind of event and let it bypass the queue and run directly, you write queue: false at the binding. That is for “small actions that do not need queuing” (say changing a single label). This chapter does not expand on it; Chapter 5 mentioned it in passing when it covered events.
The consequences of turning the queue off need to be clear. That event is no longer bound by the concurrency limit or the queue limit: one click starts one, a hundred clicks start a hundred. What you get in exchange is “immediacy”. The front end does not wait in the queue and gets the result at once. So queue: false only suits actions that “take almost no time” — changing a label, toggling a panel’s visibility. Any action that touches files, the network, or a database should not turn it off.
One more easily overlooked thing: the queue is application-level, not page-level. This is especially obvious in a multi-page application (Chapter 18), where a slow task on one page occupies a slot on another. All events of the same application (no matter which module or page) share this one queue and this one limit. So “the queue module is stuck and the other modules cannot be clicked either” is by design.
15.2 The Default Concurrency Limit
Write no concurrency parameter at all — how many can one binding run at once? One. This answer is more conservative than many people expect. After all, the default gives the impression of “handling several requests at once”. But for a handler function, “running one at a time” is the state least likely to go wrong, and the framework chose the conservative end.
You can see the effect of this default with two clicks: the second has to wait for the first to finish. What the user sees is “I pressed it and nothing happened, then it moved a moment later”. If the first run is slow, the experience is “it is stuck”.
Why is the default 1 and not “unlimited”? Because 1 is the safest starting point. When a handler function is called twice at the same time, the most likely problems are shared state being trampled (both read, both write, the later write overwrites the earlier) and downstream being overwhelmed (both query the database, the connection pool is not enough). 1 keeps both risks outside the door, and the cost is only “a bit slower”. The criterion for choosing a default is “even if it is wrong, nothing bad happens”, not “fastest”.
When should you raise it? Look at what the handler function is waiting on. If it is waiting on the network, on disk, on downstream (that is, IO-bound), raising it pays off. Open a few more and other tasks can run during that waiting time. If it is computing, transcoding, compressing images (CPU-bound), raising it does not pay off — the machine only has those few cores, opening more just makes each one slower and uses more memory. This judgment matters more than memorizing the parameter. Set the concurrency limit by “what it is waiting on”.
After raising it, watch two things. Memory (every running task holds its own copy — images, arrays, models all live in memory) and downstream (database connection pools, rate limits of third-party APIs). You relaxed your side of the application, but downstream may not be able to take it. Throttling belongs upstream, but your application is the one that gets blamed.
Verifying this yourself is simple. Set one binding to a limit of 1 and another to a limit of 2, click each twice, and look at “how many were running on entry” in the log. The group set to 1 is always 1, the group set to 2 reaches 2. The sample’s A and B groups are exactly this comparison; change the number in ConcurrencyLimit.Of(2) and run it once to see.
ConcurrencyLimit has three states, not one number.
ConcurrencyLimit.ApplicationDefault. Use the application default (that is, 1); if you write nothing, this is it;ConcurrencyLimit.Of(n), at most n;ConcurrencyLimit.Unlimited, no limit.
Why not a single int?? Because null already means “use the default”, so “unlimited” has no value left to represent it. Three states, three values — someone reading the code does not have to guess which meaning null has.
The n of Of(n) must be greater than zero; writing 0 or a negative number throws. To “not allow it to run”, do not use 0 — use the opposite of Unlimited, that is, do not bind this event at all.
Where does the default 1 come from? There is also an application-level “default concurrency limit”, which Queue(defaultConcurrencyLimit: ...) can change. The sample does not change it, so every binding that writes no concurrencyLimit is 1; one that writes its own uses its own. The relationship between the two levels is “binding level overrides application level, application level overrides framework default”.
Use Unlimited with care. It means “run as many as come”, and the queue has no effect on it. The limit gate might as well not exist for it. Scenarios that truly need it are rare. A purely read, extremely fast, stateless interface, say “get the current time”. In every other case, writing a large number (say 8) is safer than writing “unlimited” — the number is one you thought about, unlimited is one you did not.
15.3 Concurrency Groups and Binding-Level Throttling
The concurrency limit is counted per group. The group is given by concurrencyId; if you do not give one, the binding’s own name is used.
The sample’s five slow tasks are split into two groups.
queue.A1.Click(() => Slow("A1"), null, [lines.Runs], apiName: "A1",
concurrencyLimit: ConcurrencyLimit.Of(1), concurrencyId: "A");
A1, A2, and A3 all write concurrencyId: "A" with a limit of 1; B1 and B2 write "B" with a limit of 2.
- Click A1, A2, A3. Only one runs, the other two wait — they compete for the same slot;
- Click B1, B2. Both run together; the group has 2 slots;
- A and B do not affect each other; A being full does not hold up B.
Figure 15-2 is the log from this experiment. Four tasks belong to A, A, B, B respectively; clicked one after another, the “running” count on entry climbs from 1 to 3. A peak of 3 means three were really running at the same time, while the fourth kept waiting.
Figure 15-2 Concurrency across three groups: A1, B1, and B2 running at the same time, peak 3
Every row in the log has entry and exit times. Put the times together and three rows overlap. While A1 is still running, B1 and B2 both entered. This is the hardest evidence of “concurrency”. What you look at is whether the times overlap.
There is a trick to reading this log: do not look at the “peak” number, look at the time. The peak is a result, the time is the process. If rows join head to tail (one exits, the next enters), that is serial; if a later row’s “entry” is earlier than the previous row’s “exit”, that is parallel.
Two things hold at once in Figure 15-2. When B1 and B2 entered, A1 was still running and the three rows’ times overlap — that is parallel. And A2 is the last to enter; when it entered, A1 had just exited, the same group has only one slot, and it waited until a slot freed up — that is queuing. Seeing both things in one figure is exactly what this section is about: the limit is counted per group, queuing within a group, parallel across groups.
This way of “proving concurrency with timestamps” is far more reliable than “it feels faster”. Real performance acceptance uses the same method. It does not look at a single run’s duration (affected by machine load); it looks at whether there is overlap.
The slow task itself is written like this.
async Task<string> Slow(string who)
{
var run = QueueDesk.Enter(who);
var released = await QueueDesk.WaitAsync();
QueueDesk.Leave(run);
return $"**Log** {who} run {run.Id}: {run.Concurrent} running on entry, peak {run.Peak}, {(released ? "released" : "timed out")}.\n\n{string.Join("\n", QueueDesk.Lines())}";
}
Enter logs an “entry”, await WaitAsync() waits for the release, Leave logs an “exit”. What it waits on is a semaphore, not Thread.Sleep.
The point of grouping is “different kinds of work each queue up separately”. In one application, exporting a report and saving a draft are two kinds of work. The former is slow and uses resources, the latter is fast and must be immediate. Put them in the same group and when export fills up, the draft cannot be saved either; split them into two groups, give each its own slots, and neither holds up the other.
What happens if you do not give concurrencyId? The group name is computed from “handler function + the target that triggers it”. The same handler function bound to the same button counts as one group; bound to two different buttons, it counts as two groups. So even if A1 and A2 do the same thing, as long as they do not write the same group name, they each run up to their own limit. This is often the real reason “the concurrency limit does not take effect”. The concurrency limit constrains one particular button.
This also explains why A2 did not enter in Figure 15-2. It competes with A1 for the same slot; as long as A1 does not leave, it keeps waiting in the queue. A queue has no concept of “cutting in line”. Within the same group, the earlier one runs first, the later one waits. How long? Until the one ahead finishes. How long is that? It depends on the handler function. So a group’s concurrency limit actually decides “how many tasks’ worth of time a user of this group waits at most”.
So the granularity of a group should follow resources, not buttons. Several bindings that use the same database, the same model, and the same external interface share one group name. They compete for the same resource, so they should share one limit. The other way round, do not force two unrelated kinds of work into one group. Doing so ties their speeds together — one slows down and the other waits along with it.
The sample deliberately gives group A three buttons. A1, A2, A3 — all the same group, all the same limit of 1. So click three and only one runs. They compete for one slot. Group B gives two slots and two buttons, so clicking two makes two run together. This comparison is the point of this section. The limit is counted per group, not per button.
15.4 The Queue Limit and Over-Limit Rejection
The concurrency limit governs “how many run”, the queue limit governs “how many wait”. Queue(maxSize: 2) means at most two can be waiting, and the third is rejected on the spot.
demo.Queue(maxSize: 2);
“Rejected on the spot” is not “silently dropped”, nor “waiting forever”. It returns an error on the spot. When you go through an API call, this is the sentence returned.
{"detail":"Queue is full. Max size is 2 and size is 2."}
When you go through the UI, it pops up a different sentence, This application is currently busy. Please try again.. The two sentences mean the same thing but are worded differently. One is for a program to read (it carries the limit and the current count), one is for a person to read.
Figure 15-3 shows what it looks like when the queue is full: A1 running, A2 and A3 waiting, and at this moment you click B1 — an “application busy” notice pops up in the top right, and a red “error” marker appears on the log panel.
Figure 15-3 When the queue is full, the click is rejected on the spot and the UI says “application busy”
Two things need to be told apart here. Queuing is normal (the first person is running, the second waits), rejection is protection (too many are waiting, and waiting any longer only makes everyone slower together). A queue with no limit keeps growing until memory or patience runs out first; with a limit, at least the rejection is explicit and retryable.
maxSize counts “those waiting”, not “those running”. So maxSize: 2 plus a concurrency limit of 1 actually holds “1 running + 2 waiting”. This detail affects how you estimate the number. First think clearly about “how many people at most may wait”, then write it; do not treat it as “total number of people”.
On that rejected click, the user sees “application busy” and the handler function is never called at all. This matters. The rejection happens before entering the queue, not as an exception thrown inside the handler function. So writing “retry logic” in the handler function is useless. It was never called. To retry, you have to do it on the user’s side. Click once more in the UI, or send once more from a script.
Retrying has its own rules too. An immediate retry is usually still full — the tasks in the queue have not left yet. The right approach is to wait a while and try again, with a limited number of attempts. Three times, one second apart, is better than “retrying forever”. A client that never gives up will pin down an already overloaded application. What it produces is exactly the pressure that kept it out in the first place.
For a script caller, this error is an HTTP 400-level rejection whose response body carries the reason. When you write a client, check for this one and give the user a “try again later”, instead of treating it as “processing failed”. The two mean different things to the user. One is “not your turn yet”, the other is “it ran but did not succeed”.
To find out how many are queued right now, ask /gradio_api/queue/status; queue_size is the total number waiting. This interface needs no session, so a single script can query it. It is just right for monitoring. If queue_size stays close to maxSize for a long time, it is time to raise concurrency or add machines.
The rejection notice carries the limit and the current count (Max size is 2 and size is 2), which is there for you to troubleshoot with. When you see those two numbers equal, you know the queue is full, not that something else went wrong.
If you do not write maxSize, it is unlimited. For local development with one user, unlimited is fine; when you serve the outside world, you must set it. This is the first gate of “do not let the application be dragged down by its own queue”.
What value is right? Look at two numbers. One is “how long a wait you can accept”, the other is “how much memory each waiting task takes”. The more people waiting, the longer users wait, and the more the server has to remember (each event has its own input parameters attached). For an internal tool with only a few users, take 5 to 10; for one open to the public, prefer small over large. Rejecting early is better than letting everyone wait together until timeout.
The sample sets it to 2 so that you can see a rejection in one go. The side effect is that while those slow tasks in the queue module are stuck, other buttons on the page get rejected too. Because the limit is one per whole application, not split by module. This is not a bug; it is exactly what “limit” means.
But one kind of button must be an exception: “Release” and “Clear log”. When the queue is full, if even the release has to queue, that is a deadlock. The waiting tasks need a release to leave, and the release needs to queue to get in. The sample writes these two bindings as queue: false so they bypass the queue and execute directly.
queue.Release.Click(ReleaseOne, null, [lines.Runs], apiName: "Release", queue: false);
queue.Reset.Click(ResetRuns, null, [lines.Runs, lines.Batch], apiName: "Clear log", queue: false);
This is the situation where queue: false is really meant to be used: an escape valve. It does not take part in queuing and is not bound by the concurrency limit, so it can always be clicked. The premise is that it really is fast. A release just increments a semaphore, a clear just clears a table — neither takes any time. Letting a slow action bypass the queue is the same as tearing out the limit gate.
15.5 Status Push Interval
The queue’s state (what position you are, roughly how much longer) has to reach the front end before anything like “Queued, position 3” can exist. There are two ways to send it, decided by Queue’s statusUpdateRate.
- Write nothing (the default), push on change. When an event enters or leaves the queue, or a task starts or ends, it recomputes once and pushes; when nothing happens, it does not push. This is the default, and the hassle-free choice. When the queue position changes, the user sees it right away.
- Write a number of seconds, push at an interval. It pushes once every that many seconds, whether or not anything changed.
When do you want the latter? When the status stream is expensive — say several hundred events are queued and every movement recomputes the estimates of all positions, which costs a lot; pushing by the second keeps the cost under control. The price is “half a beat behind”. The position the user sees may be one interval behind reality.
There is a more practical reason too, when there are many front-end connections. “Push on change” means every movement of the queue pushes a message to every connected page; with a hundred pages connected, every task the queue completes is a hundred messages. Pushing by the second is one batch per second no matter how many pages. The cost changes from “proportional to the number of events” to “proportional to the number of seconds” — a completely different order of magnitude.
This parameter’s name is easy to misunderstand. statusUpdateRate sounds like “the rate of status updates”, but it only takes effect when you are “not pushing on change”. To keep “push on change”, do not write it; to switch to pushing by the second, write a number of seconds. The two modes are an either-or choice.
Why is “push on change” the default? Because most uses of a queue are “a few people”, where state changes are infrequent, so pushing on change is both hassle-free and fresh. Pushing by the second is for “many people”. At that point the cost of “fresh” is too high, so being half a beat behind is preferable. This trade-off is the same kind as maxSize in 15.4. At small scale, do whatever is comfortable; at large scale, you have to do the math.
The sample does not change this item and runs on the default. This setting does not show up in screenshots. A single frame cannot capture “rhythm”, just as a photograph cannot capture a heartbeat. What can be said is its effect. With the default, you click a button and the queue position changes immediately; set it to 3 seconds and it changes only at the next three-second mark.
To verify it yourself, open two tabs. In one, click a slow task to hold it up; in the other, click a few times and watch when “Queued, position N” changes. In the default mode it changes every time an event enters; switch to pushing by the second and it jumps on a fixed rhythm. This experiment needs no code changes, just one line changed to Queue(statusUpdateRate: 3).
So for this “status push interval” parameter, reading the contract is more reliable than looking at screenshots. Its effect is “how often it changes”, while a screenshot only has “what it is right now”. For evidence, use two tabs with a stopwatch, or capture a stretch of the status stream and count the messages.
There is one thing in the queue’s state that “looks like it but is not”: the progress reported by the handler function itself. Both show a progress bar in the UI, but one is “how many people are ahead of you” and the other is “what percentage of this job is done”. The former is computed by the queue, the latter is reported by the handler function (Chapter 16). Mix the two up and you get “a progress bar that jumps back and forth”, because the two sources are fighting over the same display slot.
15.6 Batching and Batch Size
There is one more way to make the queue more worthwhile: batching. Collect several events and merge them into one call.
queue.Batch.Click(BatchRun, [queue.Value], [lines.Batch], apiName: "Batch run", batch: true, maxBatchSize: 3);
batch: true turns it on, maxBatchSize: 3 says it collects at most three at a time. Once it is on, the handler function’s signature changes. It is no longer “one value” but a batch of values, object[].
string BatchRun(object[] values) => "**Batch** " + QueueDesk.Take(values);
When does it collect? When several events for the same binding are queued. Three requests arrive almost at the same time, the queue merges the three into one call, and the handler function receives one object[] with three values inside. What you save is “the fixed overhead of each call”. Opening a connection, loading a model, starting a transaction — once versus three times is a big difference.
To be concrete, a hundred records need a database lookup. Without batching that is a hundred round trips; batched into ten batches, it is ten. Say the network latency of each round trip is 2 milliseconds: the former is 200 milliseconds on the wire alone, the latter 20. What you save is “waiting”. Batching pays off most for “operations with a fixed overhead” and barely at all for “pure CPU computation”. Add three numbers up and the total CPU is the same whether you compute once or three times; batching only saves “the call” itself.
maxBatchSize is “how many at most in one batch”. Write 3 and it collects at most 3; when a 4th comes in, the first 3 go as one batch and it starts a new one. Write it too large and the first user waits a long time; write it too small and you save almost nothing. There is no formula for this number — it depends on your own tolerance for latency.
Run it once and you can see it. Three concurrent requests merge into one call, and the array the handler function receives holds three values. What to watch out for is that order is not guaranteed. That time it received v3, v2, v1, the reverse of the order sent. Batching suits scenarios where “several values are independent and handled the same way” (batch transcoding, batch database lookups), and not scenarios where “order matters” — do not turn it on for those.
What “order is not guaranteed” looks like in code is as follows. In a batch handler function, do not assume “the first element arrived earliest”. To process in order, carry a sequence number or timestamp in the value and sort it yourself when handling. This is exactly the opposite of Chapter 13’s “the array order is the UI order”. There, order is a contract; here, order is an accident.
The return value has to change along with it too. Be careful when pairing batching with state. One call handles three values, but there is only one state. If all three values need to be written into the same state, you have to loop through the writes within that one call. What you write is “the final state after this batch”. If each value needs “read state, modify, write back”, batching squeezes them into the same call and you lose the semantics of processing them one by one. Do not turn batching on for this kind of scenario.
The input of batching is object[]; what about the output? If you handle three at once and only want to return one result, return one; if each needs its own, return an array. The sample returns just one sentence (“3 in this batch. …”) because it is only demonstrating that “they were collected”. Real batching usually “returns one summary per batch”, or returns nothing at all (write it into the database and you are done).
Batching has a cost too. Handle three at once and the first user has to wait until all three are collected (or until maxBatchSize is reached) before starting; if they cannot be collected, it keeps waiting until some other mechanism lets it out. So the choice of batch size is a trade-off between “throughput” and “latency” — larger is more economical, smaller feels more responsive.
Batching is not easy to trigger from the UI. A button is disabled after one click, so you cannot produce a second event. To really try it, open two tabs and click at the same time, or fire several requests concurrently through the API. The sample’s “Batch run” button is mainly so you can see the signature: it accepts an object[], not a single value.
This also shows who the real user of batching is. “One person clicking repeatedly” does not count; “many people clicking at once” or “a script submitting in bulk” does. The former can never be collected in the UI (the button gets disabled), the latter is where batching shines. So when deciding whether to turn batching on, look at “will this interface be called concurrently”, not “will the user click repeatedly”.
15.7 Chapter Summary
The queue is on by default. Every event first enters the queue, which then decides when it runs. The three gates each govern one thing. maxSize governs how many are waiting, concurrencyId governs how they are grouped, and concurrencyLimit governs how many run at once. The parameters are written at two levels. The application-level Queue(...) sets the queue limit and the default concurrency; the binding-level Click(...) sets which group a single event belongs to and how many can run.
The default concurrency limit is 1, which means one binding runs only one at a time. ConcurrencyLimit has three states: use the default, at most n, and unlimited. It uses three values instead of one int? because null already means “use the default”.
Concurrency is counted per group. Bindings in the same group share one limit, different groups each queue up separately. The sample’s group A has 1 slot and group B has 2; click three tasks and the “running” count on entry climbs from 1 to 3, which is the hardest evidence of concurrency.
When the queue is full, it rejects on the spot rather than queuing silently. The API returns Queue is full. Max size is 2 and size is 2., and the UI pops up “This application is currently busy. Please try again.”. The limit is one per whole application, not split by module.
Queue state pushes on change by default, and can be changed to push by the second. This setting does not show up in screenshots and can only be read from the contract; what you can observe is its effect — how fast the queue position refreshes.
Batching collects several events into one call, the handler function accepts an object[], and maxBatchSize sets how many at most in one batch. What it saves is the fixed overhead of each call; the cost is that the first user has to wait until the batch is collected, and order within a batch is not guaranteed. When deciding whether to turn it on, look at “will this interface be called concurrently”, not “will the user click repeatedly”. There is a more direct criterion too. Does the handler function have “a fixed cost paid on every call”? If it does (connecting to a database, loading a file, calling a remote service), batching can save it; if it does not (pure computation), batching only piles up latency.
Beyond the four parameters there is one more use: the concurrency limit can serve as a lock. When the same state is written by two events, put the two events in the same group with a limit of 1 and they become serial. It is simpler than adding a lock in your own code, and more reliable too (forgetting to release a lock deadlocks, a queue does not).
There is one easily overlooked pairing: the queue and state are used together. If two events of the same session run at the same time, they read the same state and the later write overwrites the earlier one (as said at the end of Chapter 14). The queue’s concurrency limit happens to prevent exactly this. Put the two events in the same group and set the limit to 1, and they become serial, so the state does not get trampled. This is the second use of the “concurrency limit” besides throttling: locking shared state.
The last point is not in the parameters, but it matters more than they do: write the handler function asynchronously. The sample’s slow task awaits a semaphore, so three really run in parallel; switch to synchronous blocking (Thread.Sleep or .Wait()) and the three line up strictly one after another. The concurrency limit is still there, but the slots never free up. This is the easiest place to go wrong in this chapter. The parameters are all correct, the way it is written is not, and the behavior changes completely.
An event enters the queue (15.1) → the group decides who runs first (15.3) → the limit decides how many run together (15.2) → too many waiting and it is rejected (15.4). Every link on this chain has a parameter, but what decides the behavior is whether the handler function is asynchronous. That belongs to how you write it, not to the parameters; write it wrong and all four parameters above are tuned for nothing.
The next chapter refines this “waiting”. It has the handler function emit results frame by frame while it computes, instead of only when it is done.