简体   繁体   English

如何在C#中使用异步和等待?

[英]How to use async and await in C#?

Here I'm checking for propertie if it is Migrated or In-Progress, If In-Progress then I do not want to wait for Web Response message from supplied URL so HttpPost method should run in Background and calling method should perform its task simultaneously. 在这里,我正在检查是否已迁移或正在进行中,如果正在进行中,则我不想等待来自提供的URL Web Response消息,因此HttpPost方法应在后台运行,并且calling method应同时执行其任务。 To acheive this functionality I used async and await in below methods. 为了实现此功能,我在以下方法中使用了asyncawait

Below is the method to Post and Get XML Response back from URL: 以下是从URL发布和获取XML响应的方法:

public static async Task<string> HttpPost(string url, string message, bool ignoreResponse = false)
{
    string lcPostData = null;
    string _XmlResponse = string.Empty;
    try
    {            
        using (var client = new HttpClient())
        {
            var httpContent = new StringContent(message, Encoding.UTF8, "application/xml");
            var SupplierLinkUri = new Uri(url);

            if (!ignoreResponse)
            {                    
                var httpResponseMessage = await client.PostAsync(SupplierLinkUri, httpContent);

                if (httpResponseMessage.StatusCode == HttpStatusCode.OK)
                    _XmlResponse =  httpResponseMessage.Content.ReadAsStringAsync().Result;
            }
            else if (ignoreResponse && !(isReservation(message)))   //message.Contains("Reservation"))
            {       
                /* I want below lines of code to run asynchronously (i.e. Run in background) So I used Task & await but it fails*/
                Task<HttpResponseMessage> httpPostTask = client.PostAsync(SupplierLinkUri, httpContent);
                HttpResponseMessage asyncPost = await httpPostTask;                 
            }
        }       
    }
    catch (Exception e)
    {       
    }
    return _XmlResponse;
}

The above method IS running without errors but I want to know whether this is a right approach to use async and await in C#, Should I need to modify my code anywhere or it is correct as per mentioned requirements? 上面的方法可以正常运行,但是我想知道这是否是在C#中使用asyncawait的正确方法,是否应该在任何地方修改我的代码,或者是否符合上述要求?

await in else-if part is not working. else-if部分不起作用, else-ifelse-if await As per documentation this should run asynchronously ie in background but currently it is not. 根据文档,它应该asynchronously运行,即在后台运行,但当前不是。

Can anyone please check and suggest what is wrong in the code? 任何人都可以检查并提出代码中的错误吗?

Is their any better way to achieve this? 他们有更好的方法实现这一目标吗?

Appreciate any suggestions and Ideas! 感谢任何建议和想法! Thanks for the help! 谢谢您的帮助!

OK - this is not what async/await are for - when you await, the method you call is run on another thread (not the UI thread), and will return control to your main method (via a continuation in the background) when it is complete. 确定-这不是异步/等待的用途-等待时,调用的方法在另一个线程(不是UI线程)上运行,并且将控制权返回给您的主方法(通过后台的继续)完成了。

The method where you 'await' will not return its result until the async call is complete. 在异步调用完成之前,您“等待”的方法不会返回其结果。

eg 例如

async Task<int> A()
{
    return await B();
}

async Task<int> B()
{
     //Call to a long running service to get your answer, e.g.
    return  await PostToClientAsynchronously();
}

//Event handler on front end.
async void SomeButton_Click() {
    txtBox1.Text = await A();
}

In the example above, the PostToClientAsynchronously will run on another thread (not the UI thread), but control will not return to set the textbox value in the event handler until after the post has completed. 在上面的示例中, PostToClientAsynchronously将在另一个线程(而不是UI线程)上运行,但是控件将不会返回以在事件处理程序中设置文本框值,直到该帖子完成为止。

I'd like to post an example for your own code, but to be perfectly honest, I'm not sure exactly what it is you want to do. 我想为您自己的代码发布一个示例,但是老实说,我不确定您要执行的操作是什么。 I suspect that the issue may be solved by extending the async methods to your UI, thus not blocking it and allowing other operations, but I'm not sure. 我怀疑可以通过将异步方法扩展到您的UI来解决此问题,从而不阻止它并允许其他操作,但是我不确定。

The other important thing about calling async/await methods is that all the methods (from the front end down), need to be marked as async, to permit correct awaiting. 调用async / await方法的另一重要事项是,所有方法(从前端向下)都需要标记为异步,以允许正确的等待。


It sounds like you are trying to run these as 'fire and forget' type methods, but these are only really any good when what you are doing does not return information that you subsequently need to act upon and where you are sure that any exceptions that may happen will not hurt your application. 听起来好像您正在尝试将这些方法作为“发射后遗忘”类型的方法运行,但是只有当您正在执行的操作不会返回您随后需要根据其采取行动的信息并且您确信在其中发生任何异常时,这些方法才真正有用。可能发生不会损害您的应用程序。 Any exceptions encountered will not bubble back up to your application. 遇到的任何异常都不会冒泡回到您的应用程序。

True fire and forget use cases are rare. 真正的开火和忘记用例的情况很少见。


More information on why it must be 'turtles all the way down' when async programming: 有关异步编程时为什么必须“彻底折腾”的更多信息:

https://msdn.microsoft.com/en-us/magazine/jj991977.aspx https://msdn.microsoft.com/zh-CN/magazine/jj991977.aspx

More information about fire and forget (making sure you read the section on 'avoid async void' in the previous article: 有关失火的更多信息(请确保您已阅读上一篇文章中的“避免异步无效”部分:

Fire and Forget approach 一劳永逸的方法

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

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