Skip to content

VSTHRD002: Don't warn when getting Result on completed task #301

@KristianWedberg

Description

@KristianWedberg

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions