Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use async without await when I don't need response

Tags:

c#

async-await

I want send a SMS from my app. SMS will send when I send a get request to an specific URL. All of my methods are async, but when I instance an HttpClient and want to use response.Content.ReadAsStringAsync(), I removed await.

I don't want to wait for response of this method and want to send a request to that URL only. Now can you tell me that is it a good solution?

This is my sample code:

public async Task<bool> SendMessage(string number, string body)
{
    var from = _config["SMSSenderSettings:FromNumber"];
        var username = _config["SMSSenderSettings:PanelUserName"];
        var password = _config["SMSSenderSettings:PanelPassword"];

        using (var client = new HttpClient())
        {
            try
            {
                var response = await client.GetAsync($"{BaseUrl}/send.php?method=sendsms&format=json&from={from}" +
                    $"&to={number}&text={body}&type=0&username={username}&password={password}");
                response.EnsureSuccessStatusCode(); // Throw exception if call is not successful

                response.Content.ReadAsStringAsync();
                return true;
            }
            catch (HttpRequestException)
            {
                return false;
            }
        }
}

I removed await from response.Content.ReadAsStringAsync();, and I get warning.

like image 270
Hussein Jahanbakhsh Avatar asked Sep 03 '17 08:09

Hussein Jahanbakhsh


People also ask

Can I call async method without await?

You can call this method with or without the await keyword. The syntax with the await keyword looks like this: Customer cust = await GetCustomerById("A123"); Using the await keyword launches the method (and any code that follows it in the calling method) on a separate thread.

What happens if I call an async function without await?

Async function without await inside We can declare a function as async without using any await . In this case, the execution is not paused and your code will be executed in a non-blocking manner (asynchronous - no waiting). It is the same as not declaring that same function with async .

Is it OK to not await async?

If you forget to use await while calling an async function, the function starts executing. This means that await is not required for executing the function. The async function will return a promise, which you can use later.

Can you use async without await C?

Consider Using async without await. think that maybe you misunderstand what async does. The warning is exactly right: if you mark your method async but don't use await anywhere, then your method won't be asynchronous. If you call it, all the code inside the method will execute synchronously.


2 Answers

That is not a good idea, somewhere in your code you should await/Wait/.Result the Task otherwise any unhandled exceptions will raise up to the application level see docs

That is the radon for the warning, the compiler doesn't want to let you shoot yourself in the foot. If you really want to go ahead with this, just put the task in a variable and never use it, although other static analysis tools might flag this.

var t = response.Content.ReadAsStringAsync();

Or if the call is not required to complete the request you might consider removing it altogether.

like image 171
Titian Cernicova-Dragomir Avatar answered Oct 01 '22 09:10

Titian Cernicova-Dragomir


If you don't want to wait for your Task you can remove the unwanted return type

public async Task SendMessage(string number, string body)
{
    var from = _config["SMSSenderSettings:FromNumber"];
    var username = _config["SMSSenderSettings:PanelUserName"];
    var password = _config["SMSSenderSettings:PanelPassword"];

    using (var client = new HttpClient())
    {
        try
        {
            var response = await client.GetAsync($"{BaseUrl}/send.php?method=sendsms&format=json&from={from}" +
                $"&to={number}&text={body}&type=0&username={username}&password={password}");
            response.EnsureSuccessStatusCode(); // Throw exception if call is not successful

            await response.Content.ReadAsStringAsync();
        }
        catch (HttpRequestException)
        {

        }
    }
}

Then you can call the SendMessage from another method like-

await SendMessage().ConfigureAwait(false);

Note: This is not recommended as you will not know if your Task completes successfully or not.

There are still other ways to achieve what you want. You might read few of these-

How to run async task without need to await for result in current function/thread?

How to safely call an async method in C# without await

like image 42
Display name Avatar answered Oct 01 '22 09:10

Display name