Bug description
VSTHR002 warns even though the task has been checked for completion or have been awaited.
It should not warn in these cases, since the task is provably completed, and Result therefore
is safe to use.
Not warning is important since the below is a common performance optimization - retrieving
Result on a completed task is roughly 2x faster than awaiting the completed task.
Edited: As @AArnott points out: guarding with IsCompleted will wrap completed exceptions
in an AggregateException. To avoid this, instead guard with IsCompletedSuccessfully (ValueTask
or .Net Core 2.x) or task.Status == TaskStatus.RanToCompletion (.Net Framework), since
a successfully completed task won't have any exceptions.
Repro steps
var task = MethodAsync();
if (!task.IsCompleted)
await task.ConfigureAwait(false);
var useTaskResult = task.Result;
Expected behavior
VSTHR002 does not trigger when the task has been checked as completed via:
IsCompleted
IsCanceled
IsFaulted
IsCompletedSuccessfully (ValueTask or .Net Core 2.x)
- awaited
Actual behavior
VSTHR002 warns even though the task has been checked for completion or have been awaited.
- Version used: 15.7
- Application (if applicable): .Net Framework 4.6.1, C#7.2
Bug description
VSTHR002 warns even though the task has been checked for completion or have been awaited.
It should not warn in these cases, since the task is provably completed, and
Resultthereforeis safe to use.
Not warning is important since the below is a common performance optimization - retrieving
Resulton a completed task is roughly 2x faster than awaiting the completed task.Edited: As @AArnott points out: guarding with
IsCompletedwill wrap completed exceptionsin an
AggregateException. To avoid this, instead guard withIsCompletedSuccessfully(ValueTaskor .Net Core 2.x) or
task.Status == TaskStatus.RanToCompletion(.Net Framework), sincea successfully completed task won't have any exceptions.
Repro steps
Expected behavior
VSTHR002 does not trigger when the task has been checked as completed via:
IsCompletedIsCanceledIsFaultedIsCompletedSuccessfully(ValueTaskor .Net Core 2.x)Actual behavior
VSTHR002 warns even though the task has been checked for completion or have been awaited.