Give a Morphic application one owned worker process, live progress, cooperative cancellation, safe repeat Start, and reliable window-close cleanup. Verify the actual scheduler and interrupted paths.
9 construction stagesTested source & checkpointsNative screenshots & demos
Before you start
Give a Morphic application one owned worker process, live progress, cooperative cancellation, safe repeat Start, and reliable window-close cleanup. Verify the actual scheduler and interrupted paths.
Install the complete support application once, then run nine small independent experiments. The focused methods beside each stage explain the implementation; full file-in sources include all UI and helper methods. Workspace blocks are expressions; chunk-format .st class files are for File List → fileIn.
Long work in a button action blocks the UI process. Instead, this model owns one worker Process and a small set of plain values: state, completedSteps, result, and cancellation flags. The Morphic window reads those values during its normal step method.
The example sums the integers from 1 to N. A short Delay in each slice makes progress visible and gives other processes a turn. It stands in for a naturally bounded piece of work; there is no file, network, or shell operation in this example. Start, Cancel, and Ping UI are ordinary button messages.
File in LQBackgroundLab.st from the File List.
Run this block. Click Ping UI to change only the UI count.
Close this window before the next independent checkpoint.
Browser · LQBackgroundLab · instance side · Accept this method
Workspace · select the complete block · Do it (Ctrl/Cmd+D). Each stage creates its own model. Close earlier tutorial windows before opening the next stage.
Construction code · follow the run instructions above
| lab |
lab := LQBackgroundLab open.
lab stage: 1.
lab worker isNil ifFalse: [self error: 'The worker should not exist yet'].
lab
Watch for: Forking work does not automatically make it responsive. A CPU-bound loop that never yields can still monopolize its priority level.
Try it: Locate the model’s plain state variables in an Inspector. Which variables are Morphs, and which are safe for the worker to update?
Expected result
The window is idle: 0/100 steps, Result: none, and UI Ping count: 0.
Stage 1 in the actual Squeak 6.1 image. The supplied Workspace block sets the state; this is a native Morphic imageForm capture.
02 · Start one background process
Create the process, store its reference, set its priority, and only then resume it. This order matters because a process may finish quickly: the reference must already belong to the model when cleanup runs.
Processor userBackgroundPriority keeps the job below normal UI work. Each slice ends with Delay>>wait, so this sample yields predictably. A lower priority alone is not a substitute for breaking expensive work into bounded slices.
The worker updates only data fields. It never sends contents:, changed, openInWorld, or a dialog message. That rule keeps Morphic activity on the UI side.
Browser · LQBackgroundLab · instance side · Accept this method
start
"Install the process reference BEFORE resuming it. Ignore repeated Start."
(closed or: [worker notNil]) ifTrue: [^ false].
cancelRequested := false. completedSteps := 0. result := nil. errorText := ''. state := #running.
worker := [self performWork] newProcess.
worker priority: Processor userBackgroundPriority.
worker resume.
self refresh.
^ true
Browser · LQBackgroundLab · instance side · Accept this method
performWork
"Worker publishes plain values. It never touches Morphs or opens dialogs."
| total |
[[
total := 0.
1 to: workSize do: [:index |
(cancelRequested or: [closed]) ifTrue: [^ self].
total := total + (self valueForStep: index).
completedSteps := index.
(Delay forMilliseconds: delayMS) wait].
(cancelRequested or: [closed]) ifFalse: [
result := total. state := #completed]
] on: Error do: [:error |
errorText := error messageText. result := nil.
(closed or: [cancelRequested]) ifFalse: [state := #failed]]]
ensure: [
closed ifTrue: [state := #closed. result := nil].
state = #running ifTrue: [state := #cancelled].
worker := nil]
Where to run this
Workspace · select the complete block · Do it (Ctrl/Cmd+D). Each stage creates its own model. Close earlier tutorial windows before opening the next stage.
Construction code · follow the run instructions above
Stage 2 in the actual Squeak 6.1 image. The supplied Workspace block sets the state; this is a native Morphic imageForm capture.
03 · Publish a result only on completion
The partial sum is a temporary variable inside performWork. It becomes the public result only after the final slice and a final cancellation/closed check. That keeps the word result unambiguous: it always means a complete successful answer.
The ensure: block releases the model’s process reference after completion, cancellation, or an error. Error handling stores a message in plain model state; the UI shows it during a refresh. A later Start clears the old result before any work begins.
Browser · LQBackgroundLab · instance side · Accept this method
valueForStep: index
^ index
Where to run this
Workspace · select the complete block · Do it (Ctrl/Cmd+D). Each stage creates its own model. Close earlier tutorial windows before opening the next stage.
Construction code · follow the run instructions above
Watch for: The small polling loop here is a bounded verification block. Do not put a wait-for-completion loop in a production button callback; return to Morphic immediately.
Try it: Set N to 20 and predict the result before running: 210.
Expected result
The worker has stopped, progress is 10/10, state is completed, and Result: 55 is shown.
Stage 3 in the actual Squeak 6.1 image. The supplied Workspace block sets the state; this is a native Morphic imageForm capture.
04 · Refresh progress on the UI process
LQBackgroundWindow>>step forwards to the model’s step, which calls refresh. The native Morphic scheduler runs the step method at a requested 50 ms interval. The worker can publish progress more often than the UI needs to redraw.
This checkpoint queues a normal deferred UI message and runs a Morphic cycle while the worker is still active. The queued message increments Ping. That is a real UI scheduling test; merely calling a model setter from the worker would not establish that the UI remains available.
The sample uses simple state publication with a single owned writer. For larger compound snapshots or several workers, use a lock, queue, or immutable snapshot with an explicit ownership rule. Do not assume arbitrary multi-field reads are a transaction.
Browser · LQBackgroundWindow · instance side · Accept this method
step
self model ifNotNil: [self model step]
Browser · LQBackgroundLab · instance side · Accept this method
step
self refresh
Browser · LQBackgroundLab · instance side · Accept this method
Workspace · select the complete block · Do it (Ctrl/Cmd+D). Each stage creates its own model. Close earlier tutorial windows before opening the next stage.
Construction code · follow the run instructions above
| lab ran |
lab := LQBackgroundLab open.
lab stage: 4; workSize: 100; delayMilliseconds: 20; start.
(Delay forMilliseconds: 60) wait.
ran := false.
WorldState addDeferredUIMessage: [lab ping. ran := true].
World doOneCycleNow.
(ran and: [lab pulse = 1 and: [lab worker notNil]])
ifFalse: [self error: 'The UI message did not run during work'].
lab
Watch for: World doOneCycleNow is used in this controlled demonstration. Normal application code should return to the UI loop and let it run itself.
Try it: Click Ping UI several times during a longer job. The count should change before the result appears.
Expected result
UI Ping count becomes 1 while the worker is still running. Progress continues to update during ordinary Morphic stepping.
Stage 4 in the actual Squeak 6.1 image. The supplied Workspace block sets the state; this is a native Morphic imageForm capture.
05 · Make repeated Start safe
Users double-click. A worker reference is also an ownership guard: if it is not nil, Start returns false and leaves that exact Process running. The model never loses the old reference by overwriting it with a second process.
Configuration changes are rejected while a worker exists. A fixed N and slice delay make the job’s promise stable from start to finish. Once the worker has naturally stopped, configuration can change again.
Browser · LQBackgroundLab · instance side · Accept this method
workSize: anInteger
worker ifNotNil: [self error: 'Wait for the active worker to stop'].
(anInteger isInteger and: [anInteger between: 1 and: 100000])
ifFalse: [self error: 'Work size must be an integer from 1 to 100000'].
workSize := anInteger
Browser · LQBackgroundLab · instance side · Accept this method
delayMilliseconds: anInteger
worker ifNotNil: [self error: 'Wait for the active worker to stop'].
(anInteger isInteger and: [anInteger between: 1 and: 1000])
ifFalse: [self error: 'Delay must be an integer from 1 to 1000 milliseconds'].
delayMS := anInteger
Where to run this
Workspace · select the complete block · Do it (Ctrl/Cmd+D). Each stage creates its own model. Close earlier tutorial windows before opening the next stage.
Construction code · follow the run instructions above
| lab original |
lab := LQBackgroundLab open.
lab stage: 5; workSize: 100; delayMilliseconds: 20; start.
(Delay forMilliseconds: 60) wait.
original := lab worker.
lab start ifTrue: [self error: 'A duplicate job was started'].
lab worker == original ifFalse: [self error: 'The worker reference changed'].
lab ping.
lab
Watch for: A boolean running flag without a process reference makes cleanup harder. Keep the owned Process so repeated starts and lifecycle checks refer to the actual job.
Try it: Try changing workSize during the run. Handle the expected Error; after completion the same change should succeed.
Expected result
The second Start returns false. There is one owned worker, and the existing progress is preserved.
Stage 5 in the actual Squeak 6.1 image. The supplied Workspace block sets the state; this is a native Morphic imageForm capture.
06 · Request cooperative cancellation
Cancel sets cancelRequested and returns immediately. The worker checks that flag before each slice and once more before publishing the result. Partial sums are discarded. The UI can briefly display Cancel requested while the current slice finishes.
Cancellation latency is bounded by the work between checkpoints plus scheduling delay. This sample has tiny computation and a short Delay. Real file reads, socket calls, or foreign code need their own timeouts or interruption policy; a flag cannot interrupt a permanently blocked primitive.
We never use Process>>terminate to kill arbitrary processes. The job cleans up through its own ensure: block and clears only its own worker reference.
Browser · LQBackgroundLab · instance side · Accept this method
requestCancel
"A request, not Process>>terminate. The worker leaves at a checkpoint."
worker ifNil: [^ false].
cancelRequested := true.
self refresh.
^ true
Where to run this
Workspace · select the complete block · Do it (Ctrl/Cmd+D). Each stage creates its own model. Close earlier tutorial windows before opening the next stage.
Construction code · follow the run instructions above
Watch for: Cancel means “stop at a checkpoint”. Do not show “cancelled” before the owned worker has actually left its work method.
Try it: Press Cancel before Start and after completion. Both should be harmless and preserve the existing state.
Expected result
The state becomes cancelled, the worker reference becomes nil, and Result remains none. The progress count can be nonzero because some slices completed.
Stage 6 in the actual Squeak 6.1 image. The supplied Workspace block sets the state; this is a native Morphic imageForm capture.
07 · Restart after cancellation
A new run is allowed after the old worker has finished cleanup. Start resets progress, result, cancellation, and error text before resuming a fresh process. This avoids a stale cancel flag immediately cancelling the next run.
Waiting until the old reference is nil also prevents an old cleanup block from clearing a newer worker’s reference. More complex applications that replace jobs while older ones are still finishing need generation tokens or another explicit ownership scheme.
Where to run this
Workspace · select the complete block · Do it (Ctrl/Cmd+D). Each stage creates its own model. Close earlier tutorial windows before opening the next stage.
Construction code · follow the run instructions above
Watch for: A restart button that immediately assigns a new worker while the old one is still stopping creates an ownership race. This lesson deliberately rejects Start during that interval.
Try it: Complete a run, start a longer one, and check that the previous result disappears immediately.
Expected result
The first run cancels. A new run finishes with 10/10 steps and Result: 55; it does not inherit the old cancellation flag.
Stage 7 in the actual Squeak 6.1 image. The supplied Workspace block sets the state; this is a native Morphic imageForm capture.
08 · Treat window close as part of the job lifecycle
SystemWindow sends windowIsClosing to its model when the native close operation succeeds. The model sets closed and cancelRequested, clears the result, and stops UI stepping. The worker then leaves at its next checkpoint.
Close is idempotent. A closed model refuses a new Start; open a fresh model for a new window. The worker’s failure handler and ensure: block give closed state precedence, so an error in a slice that ends after close cannot revive the UI or publish a result.
The checkpoint closes the actual native window and opens an Inspector on four final values. The order is closed, worker, result, state. The closed application window is gone; the Inspector is a separate debugging tool.
Browser · LQBackgroundLab · instance side · Accept this method
windowIsClosing
self close.
^ super windowIsClosing
Browser · LQBackgroundLab · instance side · Accept this method
close
"Idempotent. No wait in the UI; the next checkpoint releases the process."
closed := true. cancelRequested := true. result := nil. state := #closed.
window ifNotNil: [window stopStepping].
^ self
Browser · LQBackgroundLab · instance side · Accept this method
Workspace · select the complete block · Do it (Ctrl/Cmd+D). Each stage creates its own model. Close earlier tutorial windows before opening the next stage.
Construction code · follow the run instructions above
Stage 8 in the actual Squeak 6.1 image. The supplied Workspace block sets the state; this is a native Morphic imageForm capture.
09 · Verify timing, failure, and repeated actions
File in LQBackgroundLabTests.st. The suite runs real Squeak Processes and bounded waits. It checks completion, partial-result discard, immediate cancellation, restart, double Start, separate model ownership, native stepping, a deferred UI message, and native window close.
Two semaphore-coordinated tests deliberately pause inside a work slice, apply Close or Cancel from the other process, and then make the slice fail. This establishes that cleanup wins over a late failure rather than depending on a lucky sleep interval.
These tests establish the behavior of this bounded example. They do not benchmark throughput or prove responsiveness for arbitrary blocking foreign calls. The exercises add a progress helper, an idle-only reset, and a sum-of-squares worker without changing the cancellation protocol.
Where to run this
Workspace · select the complete block · Do it (Ctrl/Cmd+D). Each stage creates its own model. Close earlier tutorial windows before opening the next stage.
Construction code · follow the run instructions above
| result inspector |
result := LQBackgroundLabTests suite run.
(result failures isEmpty and: [result errors isEmpty])
ifFalse: [self error: 'Open the Test Runner to inspect failures'].
inspector := Inspector openOn: {result runCount. result passedCount. result failures size. result errors size}.
inspector setLabel: 'Background SUnit: run / passed / failed / errors'.
inspector model selectionIndex: 1.
inspector
Watch for: Tests should wait for a condition with a deadline, not assume a single fixed sleep guarantees completion on every machine.
Try it: Run the suite again. Repeated execution should remain green and leave no active tutorial worker.
Expected result
The native Inspector displays #(16 16 0 0). Every worker created by the tests is stopped through its own cancellation/completion path.
Stage 9 in the actual Squeak 6.1 image. The supplied Workspace block sets the state; this is a native Morphic imageForm capture.
Watch the workflow
Screenshots are native Morphic imageForm captures produced by the real Squeak VM. GIFs assemble those native frames from scripted message sequences. They are not mouse recordings, browser re-creations, or performance benchmarks.
NATIVE SQUEAK CAPTURE
Scripted native-render capture of a real Process: progress advances and deferred UI Ping messages run before the complete result is published. Frames are sampled from the VM; timing is illustrative, not a benchmark.
NATIVE SQUEAK CAPTURE
Scripted native-render capture: a running job is cancelled with no result, then a fresh job completes. The Process is real; the Start/Cancel messages are automated, not recorded mouse input.
Practice with tested solutions
1. Expose percentage complete
Add percentageComplete using integer arithmetic and clamp it to 100. The model already rejects N = 0.
Show a tested solution
Browser · LQBackgroundLab · instance side · exercise solutions protocol · Accept the one method. Alternatively, file in BackgroundExercises-Solutions.st.
Workspace · select the entire check block · Print it (Ctrl/Cmd+P), after installing the solution.
Check the solution
LQBackgroundLab new percentageComplete = 0
true
2. Add an idle-only reset
Add resetWhenIdle. Return false while a worker exists or after close; otherwise reset progress, result, error and cancellation to idle.
Show a tested solution
Browser · LQBackgroundLab · instance side · exercise solutions protocol · Accept the one method. Alternatively, file in BackgroundExercises-Solutions.st.
Subclass LQBackgroundLab as LQSquaresLab. Override valueForStep: to return index squared and jobTitle to describe the calculation. Inherit Start, Cancel, and Close unchanged.
Show a tested solution
File List → fileIn this complete chunk source. It defines LQSquaresLab, then installs valueForStep: and jobTitle on LQSquaresLab’s instance side in the exercise solutions protocol. Alternatively, file in BackgroundExercises-Solutions.st.
Exercise solution
LQBackgroundLab subclass: #LQSquaresLab
instanceVariableNames: '' classVariableNames: '' poolDictionaries: ''
category: 'LearnSqueak-Background-Exercises'!
!LQSquaresLab methodsFor: 'exercise solutions'!
valueForStep: index
^ index squared
! !
!LQSquaresLab methodsFor: 'exercise solutions'!
jobTitle
^ 'A cooperative worker: sum of squares from 1 to N'
! !
Expected
For N = 10, result is 385. Cancellation still yields state cancelled and result nil.
Real process completion, cooperative cancel, discard partial result, immediate/idle Cancel, repeat Start, restart, reset old result, UI deferred message during work, native stepping, window close, separate ownership, error cleanup, semaphore-coordinated close/cancel during a failing slice.
Close the application window to request cancellation and stop stepping. Its owned worker finishes its current slice and exits. Open a new model to begin after close. No global process scan or arbitrary terminate is used.
Squeak official downloads — The native image source is the API reference: inspect Process, ProcessorScheduler, Delay, WorldState, and SystemWindow in the Browser.