简体   繁体   English

当我不需要响应时,使用async而不等待

[英]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. 当我将get请求发送到特定URL时,SMS将发送。 All of my methods are async, but when I instance an HttpClient and want to use response.Content.ReadAsStringAsync() , I removed await . 我的所有方法都是异步的,但是当我实例化HttpClient并想要使用response.Content.ReadAsStringAsync() ,我删除了await

I don't want to wait for response of this method and want to send a request to that URL only. 我不想等待此方法的响应,并且只想向该URL发送请求。 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(); 我从response.Content.ReadAsStringAsync();删除了await 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- 然后你可以从另一种方法调用SendMessage ,如 -

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 如何在没有等待的情况下在C#中安全地调用异步方法

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 这不是一个好主意,在你的代码中你应该await / Wait / .Result Task否则任何未处理的异常将提升到应用程序级别请参阅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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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