Desktop threading and accessibility
Desktop threading and accessibility
Desktop controls generally belong to the UI thread that created them. Keep event handlers short, perform bounded work away from the UI thread when useful, and marshal results back to the owning dispatcher. Accessibility is part of the same interaction contract: a responsive window must also be operable by keyboard and assistive technology.
WPF uses a Dispatcher; WinForms uses its message loop and Control.InvokeAsync on .NET 9 and later. Synchronous blocking on a task that needs the UI thread can deadlock. Task.Run can move CPU-bound work; asynchronous I/O should normally be awaited directly. An async event handler is an exception to the usual avoid-async-void rule: it needs local exception handling and lifetime ownership. Guard overlapping refreshes, cancel work when the window closes and do not write to disposed controls. In WinForms, InvokeRequired can be false before an appropriate control handle exists, even on the wrong thread. Begin work only after UI initialization and marshal through the initialized owner; a prior IsDisposed check alone cannot prevent a later close. In WPF, CheckAccess tests dispatcher access but does not schedule work. Recheck lifetime and request generation on the UI thread before applying queued results. Accessibility checks include Tab/Shift+Tab, accessible names, visible focus, screen reader reading order, large text, high contrast and DPI/resizing. Windows UI Automation behavior needs an actual supported Windows test; no metadata alone guarantees accessibility.
Baseline: .NET 10 / C# 14. Every expected result is reasoned, not executed. The complete portable and Windows desktop projects are separate from MAUI template overlays. No runtime or UI claims.
Return a bounded result to the dispatcher
Press Refresh once and wait for status. Close during a refresh to exercise the lifetime guard.
Use an approved Windows .NET 10 environment. Build the complete Fixture.csproj after approved restore; run it and close the window when finished.
using System;using System.Windows;namespace Fixture;public static class Program { [STAThread] public static void Main() => new Application().Run(new InventoryWindow());}public partial class InventoryWindow : Window { private bool busy, closed; public InventoryWindow() { InitializeComponent(); Closed += (_,_) => closed=true; } private async void Refresh(object sender, RoutedEventArgs e) { if(busy) return; busy=true; RefreshButton.IsEnabled=false; try { var dispatcher=Dispatcher; await System.Threading.Tasks.Task.Run(async () => { int sum=0; for(int i=1;i<=1000;i++) sum+=i; await dispatcher.InvokeAsync(() => { if(!closed) Status.Text=$"Total: {sum}"; }); }); } catch (OperationCanceledException) when (closed || Dispatcher.HasShutdownStarted) { /* closed lab */ } catch (Exception) { if(!closed) Status.Text="Refresh failed"; } finally { if(!closed) { busy=false; RefreshButton.IsEnabled=true; } } }}InventoryWindow.xaml
<Window x:Class="Fixture.InventoryWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Inventory lab" Width="440" Height="260" MinWidth="320" MinHeight="220"> <StackPanel Margin="16"> <Button x:Name="RefreshButton" Content="_Refresh" Click="Refresh" AutomationProperties.Name="Refresh inventory"/> <TextBlock x:Name="Status" Margin="0,12,0,0" Text="Ready"/> </StackPanel></Window>Expected result (not executed):
Eventually Total: 500500 and Refresh enabled, if window remains open.A small finite computation is marshaled back to the dispatcher. It is not a timing benchmark; the close guard prevents an update after closure. For longer jobs use cancellation.
Check keyboard and accessible names
Use Tab and Shift+Tab, type a note, then activate Preview with Space.
Use an approved Windows .NET 10 environment. Build the complete Fixture.csproj after approved restore; run it and close the window when finished.
using System;using System.Drawing;using System.Windows.Forms;using System.Threading.Tasks;namespace Fixture;public static class Program { [STAThread] public static void Main() { ApplicationConfiguration.Initialize(); Application.Run(new InventoryForm()); }}public sealed class InventoryForm : Form { public InventoryForm() { Text="Accessible inventory"; ClientSize=new Size(400,220); AutoScaleMode=AutoScaleMode.Dpi; var panel=new TableLayoutPanel { Dock=DockStyle.Fill, ColumnCount=1, RowCount=4, Padding=new Padding(12), AutoScroll=true }; var label=new Label { Text="&Note", AutoSize=true, TabIndex=0 }; var entry=new TextBox { AccessibleName="Inventory note", Dock=DockStyle.Top, TabIndex=1 }; var button=new Button { Text="&Preview", AutoSize=true, TabIndex=2 }; var output=new Label { Text="No preview", AutoSize=true, AccessibleName="Preview result" }; panel.Controls.Add(label,0,0); panel.Controls.Add(entry,0,1); panel.Controls.Add(button,0,2); panel.Controls.Add(output,0,3); Controls.Add(panel); button.Click += (_,_) => output.Text=$"Preview: {entry.Text}"; }}Expected result (not executed):
Entry then Preview in keyboard traversal; Preview: Atlas after typing Atlas and activating.Names and native controls provide accessibility hooks. Verify the actual announced result, focus order and clipping on Windows, rather than assuming success.
Reject a stale refresh result
Model generation numbers before connecting to a dispatcher.
Use the complete Fixture.csproj with an approved .NET 10 SDK. Restore approved dependencies, build and run. No UI workload needed.
using System;int latest=2;string display="Loading";void Apply(int generation,string value) { if(generation==latest) display=value; }Apply(2,"New stock");Apply(1,"Old stock");Console.WriteLine(display);Expected result (not executed):
New stockA generation check rejects an older completion. In a UI, serialize the comparison and update on the UI thread; this console model does not exercise races.
Apply the concept
Describe a cancellable inventory refresh that may complete after a new refresh or after close. Include keyboard and DPI test steps.
Use the manual practice and knowledge check. Do not deploy or publish these fixtures.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Desktop threading and accessibility — knowledge check
Apply the lesson concepts to the following scenarios.
Where should control updates be made?
What does Dispatcher.InvokeAsync do?
Which WinForms method offers async-friendly marshaling in .NET 9+?
What prevents an old refresh from overwriting newer results?
What is required to assess keyboard usability?