How do you run CPU-bound work without blocking the UI?
Short answer
Offload CPU-bound work with Task.Run so it executes on a thread-pool thread, await the result, then update UI on the main thread. Don't use Task.Run for I/O (await the async API directly). Keep the UI responsive by never blocking it with .Result or .Wait().
Advertisement
AModel answer
Offload CPU-bound work with Task.Run so it executes on a thread-pool thread, await the result, then update UI on the main thread. Don't use Task.Run for I/O (await the async API directly). Keep the UI responsive by never blocking it with .Result or .Wait().
var result = await Task.Run(() => ExpensiveCompute(data));
resultLabel.Text = result.ToString(); // back on UI thread after awaitReal-world example
Image processing runs on a background thread via Task.Run so the UI stays responsive, then shows the result.
Likely follow-ups
- Why not Task.Run for I/O? | Why avoid .Result?
Related topics