How to create an inactive async method stub?

Viewed 141

This is a simple question, but when I was starting with async/await, it cost me hours to resolve and I couldn't easily find any answers. Hopefully this will help others who run into the same issue.

When creating a class, I often frame it out by creating a number of inactive method stubs and I don't want to throw NotImplemented exceptions or see warnings about the methods not being awaited. These methods should be callable, but should just do nothing.

So, how do I to create inactive async methods?

1 Answers

How to create inactive async methods

  • For methods that do not return a value, add: await TaskCompleted;
  • For methods that do return a value, add: await Task.FromResult(0); // (for int result, other values for other types)

Examples

    // No return value:
    private async Task SampleNoReturn1()
    {
        await Task.CompletedTask;
    }

    // No return value with optional Cancellation Token:
    // Note: To make the token mandatory, remove the "=default"
    private async Task SampleNoReturn2(CancellationToken cancelToken=default)
    {
        await Task.CompletedTask;
    }
    // With a return value:
    // For other return types, change the "0" in the 
    // return statement to an appropriate value.
    private async Task<Int32> SampleWithReturnValue1()
    {
        return await Task.FromResult(0);
    }

    // With a return value  with optional Cancellation Token:
    // Note: To make the token mandatory, remove the "=default"
    private async Task<Int32> SampleWithReturnValue2(CancellationToken cancelToken = default)
    {
        return await Task.FromResult(0);
    }
Related