Files
Terminal.Gui/docfx/docs/multitasking.md
Tig a6258ed398 Updates IListDataSource.Render to rename the start parameter to viewportXOffset (#4392)
* Add comprehensive unit tests for WindowsKeyConverter

- Implement 118 parallelizable unit tests for WindowsKeyConverter

- Cover ToKey and ToKeyInfo methods with full bidirectional testing

- Test basic characters, modifiers, special keys, function keys

- Test VK_PACKET Unicode/IME input

- Test OEM keys, NumPad keys, and lock states

- Include round-trip conversion tests

- All tests passing successfully

Fixes #4389

* Rename `start` parameter to `viewportXOffset` for clarity

The `start` parameter in several methods and interfaces has been
renamed to `viewportXOffset` to better reflect its purpose as the
horizontal offset of the viewport during string rendering.

- Updated method signatures in `ListViewWithSelection` to use
  `viewportXOffset` instead of `start`, including default values.
- Modified the `RenderUstr` method in `ListViewWithSelection` to
  use `viewportXOffset` for calculating the starting index.
- Renamed the `start` parameter to `viewportXOffset` in the
  `IListDataSource` interface and updated its documentation.
- Replaced all occurrences of `start` with `viewportXOffset` in
  the `ListWrapper<T>` class, including method calls and logic.
- Updated the `RenderUstr` method in `ListWrapper<T>` to use
  `viewportXOffset` for substring calculations.
- Adjusted the test method in `ListViewTests.cs` to reflect the
  parameter name change.

These changes improve code readability and make the parameter's
role in rendering logic more explicit.

* Remove WindowsKeyConverterTests class that was added by mistake

* Modernized ListView and IListDataSource - Tons of new unit tests

Refactored `ListView` and `IListDataSource` to improve readability, maintainability, and functionality. Introduced `ListWrapper<T>` as a default implementation of `IListDataSource` for easier integration with standard collections.

Enhanced `ListView` with better handling of marking, selection, and scrolling. Replaced `viewportXOffset` with `viewportX` for horizontal scrolling. Added `EnsureSelectedItemVisible` to maintain visibility of the selected item.

Updated `IListDataSource` with detailed XML documentation and added `SuspendCollectionChangedEvent` for bulk updates. Improved null safety with nullable reference types.

Added comprehensive unit tests for `ListWrapper<T>` and `IListDataSource` to ensure robustness. Modernized the codebase with C# features like expression-bodied members and pattern matching. Fixed bugs related to `SelectedItem` validation and rendering artifacts.

* Improve index validation in ComboBox and ListView

Enhance robustness by adding stricter checks for valid indices
in ComboBox and ListView. Updated conditions in the
`_listview.SelectedItemChanged` event handler to ensure `e.Item`
is non-negative before accessing `_searchSet`. Modified the
`SetValue` method to use `e.Item` instead of `_listview.SelectedItem`.

In ListView, updated the `OnSelectedChanged` method to validate
that `SelectedItem` is non-negative (`>= 0`) before accessing
the `Source` list. These changes prevent potential out-of-range
errors and improve code safety.

* Refactor and enhance test coverage across modules

Refactored and added new tests to improve coverage, readability, and consistency across multiple test files. Key changes include:

- **ShortcutTests.cs**: Added tests for `BindKeyToApplication` and removed redundant tests.
- **SourcesManagerTests.cs**: Renamed `Update_*` tests to `Load_*` for clarity.
- **ArrangementTests.cs**: Reintroduced `MouseGrabHandler` tests, added `ViewArrangement` flag tests, and improved structure.
- **NeedsDrawTests.cs**: Replaced `Application.Screen.Size` with fixed dimensions for better isolation.
- **DimAutoTests.cs**: Updated layout tests to use fixed dimensions.
- **FrameTests.cs**: Standardized object initialization and validated frame behavior.
- **SubViewTests.cs**: Improved formatting and modernized event handling.
- **NumericUpDownTests.cs**: Decoupled layout tests from screen size.

General improvements:
- Enhanced formatting and removed redundant tests.
- Added comments for clarity.
- Introduced `ITestOutputHelper` for better debugging in `ArrangementTests`.

* Refactor to use nullable types for better null safety

Enabled nullable reference types across the codebase to improve null safety and prevent potential null reference issues. Refactored `SelectedItem` and related properties from `int` to `int?` to represent no selection with `null` instead of `-1`. Updated logic, event arguments, and method signatures to handle nullable values consistently.

Simplified object initialization using modern C# syntax and improved code readability with interpolated strings. Added null checks and early returns to prevent runtime errors. Enhanced error handling by throwing `ArgumentOutOfRangeException` for invalid values.

Updated tests to reflect the changes, replacing assertions for `-1` with `null` and ensuring proper handling of nullable values. Cleaned up redundant code and improved formatting for better maintainability.

* on` functionality has been deprecated, refactored, or removed from the `Shortcut` class.

* Refactor: Transition to instance-based architecture

Updated `Run-LocalCoverage.ps1` to increase `--blame-hang-timeout` from 10s to 60s. Improved null safety in `GuiTestContext` by adding null-conditional operators. Commented out problematic code in `SetupFakeApplicationAttribute.cs` to prevent test hangs.

Excluded `ViewBase` files from `UnitTests.Parallelizable.csproj` and removed redundant folder declarations. Simplified event handling in `IListDataSourceTests.cs` and updated `ListViewTests.cs` to use nullable reference types.

Enhanced documentation to emphasize the transition to an instance-based application architecture. Updated examples in `application.md`, `multitasking.md`, and `navigation.md` to reflect the use of `Application.Create()` and `View.App`. Clarified the obsolescence of the static `Application` class.

Revised table of contents in `toc.yml` to include new sections like "Application Deep Dive" and "Scheme Deep Dive." Added `dotnet-tools.json` for tool configuration.

These changes improve maintainability, testability, and alignment with modern C# practices.

* Refactor ListViewTests to use Terminal.Gui framework

The `ListViewTests` class has been refactored to replace the `AutoInitShutdown` attribute with explicit application lifecycle management using `IApplication` and `app.Init()` from the `Terminal.Gui` framework.

Key changes include:
- Rewriting tests to use `Terminal.Gui`'s application lifecycle.
- Adding a private `_output` field for logging test output via `ITestOutputHelper`.
- Updating `DriverAssert.AssertDriverContentsWithFrameAre` to include `app.Driver` for UI verification.
- Rewriting tests like `Clicking_On_Border_Is_Ignored`, `EnsureSelectedItemVisible_SelectedItem`, and others to align with the new framework.
- Adding explicit calls to `app.Shutdown()` for proper cleanup.
- Enabling nullable reference types with `#nullable enable`.
- Updating `using` directives and `namespace` to reflect the new structure.

These changes improve test maintainability, compatibility, and diagnostics.

* Update Terminal.Gui/Views/CollectionNavigation/CollectionNavigatorBase.cs

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update Terminal.Gui/Views/CollectionNavigation/CollectionNavigatorBase.cs

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update Examples/UICatalog/UICatalogTop.cs

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update Terminal.Gui/Views/ListWrapper.cs

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update Terminal.Gui/Views/ListWrapper.cs

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Updated the `SetMark` method to return `Source.IsMarked(SelectedItem.Value)` for consistency and removed an outdated comment questioning its correctness.

Enhanced the exception message in the `SelectedItem` property setter to provide clearer guidance when the value is out of range.

* Add comprehensive ListView behavior test coverage

Added multiple test methods to validate `ListView` behavior:
- `Vertical_ScrollBar_Hides_And_Shows_As_Needed`: Ensures the vertical scrollbar auto-hides/shows based on content height.
- `Mouse_Wheel_Scrolls`: Verifies vertical scrolling with the mouse wheel updates `TopItem`.
- `SelectedItem_With_Source_Null_Does_Nothing`: Confirms no exceptions occur when setting `SelectedItem` with a `null` source.
- `Horizontal_Scroll`: Tests horizontal scrolling, including programmatic and mouse wheel interactions, ensuring `LeftItem` updates correctly.
- `SetSourceAsync_SetsSource`: Validates the asynchronous `SetSourceAsync` method updates the source and item count.
- `AllowsMultipleSelection_Set_To_False_Unmarks_All_But_Selected`: Ensures disabling multiple selection unmarks all but the selected item.
- `Source_CollectionChanged_Remove`: Confirms `SelectedItem` and source count update correctly when items are removed from the source collection.

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-19 20:39:34 -05:00

295 lines
7.4 KiB
Markdown

# Multitasking and Background Operations
_See also [Cross-platform Driver Model](drivers.md)_
Terminal.Gui applications run on a single main thread with an event loop that processes keyboard, mouse, and system events. This document explains how to properly handle background work, timers, and asynchronous operations while keeping your UI responsive.
## Threading Model
Terminal.Gui follows the standard UI toolkit pattern where **all UI operations must happen on the main thread**. Attempting to modify views or their properties from background threads will result in undefined behavior and potential crashes.
### The Golden Rule
> Always use `Application.Invoke()` (static, obsolete) or `app.Invoke()` (instance-based, recommended) to update the UI from background threads. From within a View, use `App?.Invoke()`.
## Background Operations
### Using async/await (Recommended)
The preferred way to handle background work is using C#'s async/await pattern:
```csharp
private async void LoadDataButton_Clicked()
{
loadButton.Enabled = false;
statusLabel.Text = "Loading...";
try
{
// This runs on a background thread
var data = await FetchDataFromApiAsync();
// This automatically returns to the main thread
dataView.LoadData(data);
statusLabel.Text = $"Loaded {data.Count} items";
}
catch (Exception ex)
{
statusLabel.Text = $"Error: {ex.Message}";
}
finally
{
loadButton.Enabled = true;
}
}
```
### Using Application.Invoke()
When working with traditional threading APIs or when async/await isn't suitable:
**From within a View (recommended):**
```csharp
private void StartBackgroundWork()
{
Task.Run(() =>
{
// This code runs on a background thread
for (int i = 0; i <= 100; i++)
{
Thread.Sleep(50); // Simulate work
// Marshal back to main thread for UI updates
App?.Invoke(() =>
{
progressBar.Fraction = i / 100f;
statusLabel.Text = $"Progress: {i}%";
});
}
App?.Invoke(() =>
{
statusLabel.Text = "Complete!";
});
});
}
```
**Using IApplication instance (recommended):**
```csharp
var app = Application.Create();
app.Init();
private void StartBackgroundWork(IApplication app)
{
Task.Run(() =>
{
// This code runs on a background thread
for (int i = 0; i <= 100; i++)
{
Thread.Sleep(50); // Simulate work
// Marshal back to main thread for UI updates
app.Invoke(() =>
{
progressBar.Fraction = i / 100f;
statusLabel.Text = $"Progress: {i}%";
});
}
app.Invoke(() =>
{
statusLabel.Text = "Complete!";
});
});
}
```
**Using static Application (obsolete but still works):**
```csharp
Application.Invoke(() => { /* ... */ });
```
## Timers
Use timers for periodic updates like clocks, status refreshes, or animations:
```csharp
public class ClockView : View
{
private Label timeLabel;
private object timerToken;
public ClockView()
{
timeLabel = new Label { Text = DateTime.Now.ToString("HH:mm:ss") };
Add(timeLabel);
// Update every second
// Use App?.AddTimeout() when available, or Application.AddTimeout() (obsolete)
timerToken = App?.AddTimeout(
TimeSpan.FromSeconds(1),
UpdateTime
) ?? Application.AddTimeout(TimeSpan.FromSeconds(1), UpdateTime);
}
private bool UpdateTime()
{
timeLabel.Text = DateTime.Now.ToString("HH:mm:ss");
return true; // Continue timer
}
protected override void Dispose(bool disposing)
{
if (disposing && timerToken != null)
{
App?.RemoveTimeout(timerToken) ?? Application.RemoveTimeout(timerToken);
}
base.Dispose(disposing);
}
}
```
### Timer Best Practices
- **Always remove timers** when disposing views to prevent memory leaks
- **Return `true`** from timer callbacks to continue, `false` to stop
- **Keep timer callbacks fast** - they run on the main thread
- **Use appropriate intervals** - too frequent updates can impact performance
## Common Patterns
### Progress Reporting
```csharp
private async void ProcessFiles()
{
var files = Directory.GetFiles(folderPath);
progressBar.Fraction = 0;
for (int i = 0; i < files.Length; i++)
{
await ProcessFileAsync(files[i]);
// Update progress on main thread
progressBar.Fraction = (float)(i + 1) / files.Length;
statusLabel.Text = $"Processed {i + 1} of {files.Length} files";
// Allow UI to update
await Task.Yield();
}
}
```
### Cancellation Support
```csharp
private CancellationTokenSource cancellationSource;
private async void StartLongOperation()
{
cancellationSource = new CancellationTokenSource();
cancelButton.Enabled = true;
try
{
await LongRunningOperationAsync(cancellationSource.Token);
statusLabel.Text = "Operation completed";
}
catch (OperationCanceledException)
{
statusLabel.Text = "Operation cancelled";
}
finally
{
cancelButton.Enabled = false;
}
}
private void CancelButton_Clicked()
{
cancellationSource?.Cancel();
}
```
### Responsive UI During Blocking Operations
```csharp
private async void ProcessLargeDataset()
{
var data = GetLargeDataset();
var batchSize = 100;
for (int i = 0; i < data.Count; i += batchSize)
{
// Process a batch
var batch = data.Skip(i).Take(batchSize);
ProcessBatch(batch);
// Update UI and yield control
progressBar.Fraction = (float)i / data.Count;
await Task.Yield(); // Allows UI events to process
}
}
```
## Common Mistakes to Avoid
### ❌ Don't: Update UI from background threads
```csharp
Task.Run(() =>
{
label.Text = "This will crash!"; // Wrong!
});
```
### ✅ Do: Use Application.Invoke()
```csharp
Task.Run(() =>
{
Application.Invoke(() =>
{
label.Text = "This is safe!"; // Correct!
});
});
```
### ❌ Don't: Forget to clean up timers
```csharp
// Memory leak - timer keeps running after view is disposed
// From within a View:
App?.AddTimeout(TimeSpan.FromSeconds(1), UpdateStatus);
// Or with IApplication instance:
app.AddTimeout(TimeSpan.FromSeconds(1), UpdateStatus);
// Or static (obsolete but works):
Application.AddTimeout(TimeSpan.FromSeconds(1), UpdateStatus);
```
### ✅ Do: Remove timers in Dispose
```csharp
protected override void Dispose(bool disposing)
{
if (disposing && timerToken != null)
{
Application.RemoveTimeout(timerToken);
}
base.Dispose(disposing);
}
```
## Performance Considerations
- **Batch UI updates** when possible instead of updating individual elements
- **Use appropriate timer intervals** - 100ms is usually the maximum useful rate
- **Yield control** in long-running operations with `await Task.Yield()`
- **Consider using `ConfigureAwait(false)`** for non-UI async operations
- **Profile your application** to identify performance bottlenecks
## See Also
- [Events](events.md) - Event handling patterns
- [Keyboard Input](keyboard.md) - Keyboard event processing
- [Mouse Input](mouse.md) - Mouse event handling
- [Configuration Management](config.md) - Application settings and state