Skip to content

Support cancellation on prompts #417

@kzu

Description

@kzu

Since it's now trivial to create async Main methods that pass around a CancellationToken to cleanly stop a running console app (i.e. System.CommandLine makes this very straightforward), it would be useful to cancel prompts by simply cancelling the token (which in System.CommandLine is done automatically when hitting Ctrl+C so the program has chance to cancel
ongoing work cleanly).

Proposed solution

An improvement of the existing Prompt methods would receive a new optional parameter and if the token is cancelled, it would immediately return the default value, instead of waiting for a selection. This allows aborting the selection by pressing Ctrl+C, for example.

public static T Prompt<T>(IPrompt<T> prompt, CancellationToken cancellation = default)
public static T Ask<T>(string prompt, CancellationToken cancellation = default)
public static bool Confirm(string prompt, bool defaultValue = true, CancellationToken cancellation = default)

Alternatives

The return value could be made nullable, so the caller could determine if an actual selection was made or if the prompt was cancelled instead.

public static T? Prompt<T>(IPrompt<T> prompt, CancellationToken cancellation = default)
public static T? Ask<T>(string prompt, CancellationToken cancellation = default)
public static bool? Confirm(string prompt, bool defaultValue = true, CancellationToken cancellation = default)

Since the caller would presumably still use the passed cancellation token to check on pending cancellation requests, it seems an unnecessary breaking change that doesn't add much value, perhaps.

I'd like to gather feedback on whether this is deemed useful and then I can work on a PR as needed.

Thanks

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions