Sobes.tech
Junior — Middle

What return value options can an async method have?

sobes.tech AI

Answer from AI

An asynchronous method in C#, marked with the keyword async, can return the following types:

  • Task — for methods that do not return a result but execute asynchronously.
  • Task<T> — for methods that return a result of type T asynchronously.
  • ValueTask and ValueTask<T> — more optimized options for asynchronous methods that can complete synchronously or asynchronously (since C# 7.0).
  • void — used only for event handlers, but not recommended for regular asynchronous methods, as it does not allow tracking completion and errors.

Example:

public async Task<int> GetDataAsync()
{
    await Task.Delay(1000);
    return 42;
}