简体   繁体   中英

Use async without await when I don't need response

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.

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

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.

If the response content is not needed, do not read the content at all. And you should not throw exceptions, when you can avoid it.

With that you can have a much cleaner 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())
    {
        var response = await client.GetAsync($"{BaseUrl}/send.php?method=sendsms&format=json&from={from}" +
            $"&to={number}&text={body}&type=0&username={username}&password={password}");
        return response.IsSuccessStatusCode();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM