harishr
harishr

Reputation: 18065

What should be the return type of async method returning nothing

I have the piece of code below which is giving analyzer warning:

    public async Task SendPasswordEmail(string emailId, string link)
    {
        await _emailSender
            .To(emailId)
            .Subject(EmailUtilsConstants.PasswordEmailSubject)
            .Body(EmailUtilsConstants.PasswordEmailText + link)
            .SendAsync();
    }

The warning I get is:

The method 'SendPasswordEmail' do not need to use async/await.

If the method should not use async await, what should be the return type? Task. So is below fix to analyser correct?

    public Task SendPasswordEmail(string emailId, string link)
    {
        _emailSender
            .To(emailId)
            .Subject(EmailUtilsConstants.PasswordEmailSubject)
            .Body(EmailUtilsConstants.PasswordEmailText + link)
            .SendAsync();
        return Task.Completed;
    }

Upvotes: 0

Views: 205

Answers (1)

Farhad Jabiyev
Farhad Jabiyev

Reputation: 26645

You can remove async and await keywords in case of single line inside function. I guess SendAsync returns Task object already, so not need to await, just return that Task:

public Task SendPasswordEmail(string emailId, string link)
{
    return _emailSender
        .To(emailId)
        .Subject(EmailUtilsConstants.PasswordEmailSubject)
        .Body(EmailUtilsConstants.PasswordEmailText + link)
        .SendAsync();
}

Async/Await will introduce additional overhead to your method. Compiler will create "state machine" for all async methods which is unnecessary in case of single line of code inside method body.

Update: (thanks for comment to @JohnathanBarclay)

Another difference in case of eliding async/awaitm the exception handling will change a bit. The state machine for async methods will capture exceptions from your code and place them on the returned task. But, it won't be case in case of eliding async/await.

Read https://blog.stephencleary.com/2016/12/eliding-async-await.html for more.

Upvotes: 11

Related Questions