← back to index

S4586 — Non-async "Task/Task<T>" methods should not return null

Language: VB.NET  |  Type: BUG  |  Severity: Critical

Tags: async-await

Why is this an issue?

Returning Nothing from a non-Async Task/Task(Of TResult) procedure will cause a NullReferenceException at runtime if the procedure is awaited. This problem can be avoided by returning Task.CompletedTask or Task.FromResult(Of TResult)(Nothing) respectively.

Public Function DoFooAsync() As Task
    Return Nothing            ' Noncompliant: Causes a NullReferenceException if awaited.
End Function

Public Async Function Main() As Task
    Await DoFooAsync()        ' NullReferenceException
End Function

How to fix it

Instead of Nothing Task.CompletedTask or Task.FromResult(Of TResult)(Nothing) should be returned.

Code examples

A Task returning procedure can be fixed like so:

Noncompliant code example

Public Function DoFooAsync() As Task
    Return Nothing            ' Noncompliant: Causes a NullReferenceException if awaited.
End Function

Compliant solution

Public Function DoFooAsync() As Task
    Return Task.CompletedTask ' Compliant: Method can be awaited.
End Function

A Task(Of TResult) returning procedure can be fixed like so:

Noncompliant code example

Public Function GetFooAsync() As Task(Of Object)
    Return Nothing                             ' Noncompliant: Causes a NullReferenceException if awaited.
End Function

Compliant solution

Public Function GetFooAsync() As Task(Of Object)
    Return Task.FromResult(Of Object)(Nothing) ' Compliant: Method can be awaited.
End Function

Resources

Documentation

Articles & blog posts