Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Version introduced: .NET 9
Task is being passed to InvokeAsync without a cancellation token
Provide a cancellation token when returning a Task or ValueTask from InvokeAsync, which ensures the delegate can be properly awaited and exceptions can be handled.
You can ignore this error if your intention is to run an unsupervised task.
To correct this warning
Use functions that take cancellation tokens as an argument. This will allow the delegate passed to InvokeAsync
to be awaited, ensuring that exceptions are handled correctly.
CancellationTokenSource _stopWatchTokenSource = new();
CancellationToken _stopWatchToken;
private async void btnStopWatch_Click(object sender, EventArgs e)
{
if (_stopWatchToken.CanBeCanceled)
{
btnStopWatch.Text = "Start";
_stopWatchTokenSource.Cancel();
_stopWatchTokenSource.Dispose();
_stopWatchTokenSource = new CancellationTokenSource();
_stopWatchToken = CancellationToken.None;
return;
}
_stopWatchToken = _stopWatchTokenSource.Token;
btnStopWatch.Text = "Stop";
await Task.Run(async () =>
{
while (true)
{
try
{
await this.InvokeAsync(UpdateUiAsync, _stopWatchToken);
}
catch (TaskCanceledException)
{
break;
}
}
});
}
// The actual UI update method
async ValueTask UpdateUiAsync(CancellationToken cancellation)
{
lblStopWatch.Text = $"{DateTime.Now:HH:mm:ss - fff}";
await Task.Delay(20, cancellation);
}
// Make sure that the token is cancelled when the form is closed
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
_stopWatchTokenSource.Cancel();
}
Manage the warning
Suppress the warning with either of the following methods:
Set the severity of the rule in the .editorConfig file.
[*.{cs,vb}] dotnet_diagnostic.WFO2001.severity = none
For more information about editor config files, see Configuration files for code analysis rules.
Add the following
PropertyGroup
to your project file:<PropertyGroup> <NoWarn>$(NoWarn);WFO2001</NoWarn> </PropertyGroup>
Suppress in code with the
#pragma warning disable WFO2001
directive.
.NET Desktop feedback