c# - 在调用异步函数后执行代码

标签 c# asp.net asynchronous curl httpclient

我有一个 async void 函数,我调用它来执行几个 curl 调用。我有代码需要在该函数执行后执行,因为在函数内部设置了一个变量。现在看起来代码是在异步函数之前执行的。有什么建议吗?

Update(allNumbers, allValues);

//result is a global variable that is set inside the Update function.

if (result.Contains("success"))
{
    message.InnerText = "Result: " + result + "\r\nSuccessfully updated value";
}
else
{
    message.InnerText = "Result: " + result + "\r\nError updating value";
}


async void Update(List<string> allNumbers, List<string> allValues){
    CookieContainer cookies = new CookieContainer();
    HttpClientHandler handler = new HttpClientHandler();
    handler.CookieContainer = cookies;
    string file = "";
    HttpRequestMessage response = new HttpRequestMessage();
    using (var client = new HttpClient(handler))
    {
        client.Timeout = TimeSpan.FromMinutes(30);
        client.BaseAddress = new Uri('Web IP');
        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/xml"));                   
            try
            {
                file = System.IO.File.ReadAllText(path + "user.xml");
                response = new HttpRequestMessage(HttpMethod.Post, 'Web Extension 1');
                response.Content = new StringContent(file, Encoding.UTF8, "application/xml");
                await client.SendAsync(response).ContinueWith(responseTask =>
                {
                    Uri uri = new Uri('Web IP' + 'Web Extension 1');
                    IEnumerable<Cookie> responseCookies = cookies.GetCookies(uri).Cast<Cookie>();
                    foreach (Cookie the_cookie in responseCookies)
                    {
                        File.WriteAllText(path + "sessionid.txt", String.Empty);
                        using (var tw = new StreamWriter(path + "sessionid.txt", true))
                            {                                    
                                // Create file with cookie information                                                     
                            }                               
                        }
                    });                        
                }                    
                catch (Exception ex)
                {
                    using (var stw = new StreamWriter(path + "error.txt", true))
                    {
                        stw.WriteLine("Error with Login cURL Call - " + ex.ToString() + "\r\n---------------------------------------------------");
                    }  
                    result = "Error with Login cURL Call -" + ex.ToString();
                }

                string id = "";                    
                try
                {                        
                    response = new HttpRequestMessage(HttpMethod.Get, 'Web Extension 2');                        
                    await client.SendAsync(response).ContinueWith(responseTask =>
                    {
                        string contents = responseTask.Result.Content.ReadAsStringAsync().Result;                            
                        //assign id value                        
                    });
                }                    
                catch (Exception ex)
                {
                    using (var tsw = new StreamWriter(path + "error.txt", true))
                    {
                        tsw.WriteLine("Error with Load Config cURL Call - " + ex.ToString() + "\r\n---------------------------------------------------");
                    }
                    result = "Error with Load Config cURL Call - " + ex.ToString();
                }
                if (id != "")
                {
                    for (int i = 0; i < allNumbers.Count; i++)
                    {                                              
                        try
                        {                                
                            file = System.IO.File.ReadAllText(path + allNumbers[i] + ".xml");                                
                            response = new HttpRequestMessage(HttpMethod.Post, 'We Extension 3.1' + id + 'Web Extension 3.2');                                
                            response.Content = new StringContent(file, Encoding.UTF8, "application/xml");                                
                            await client.SendAsync(response).ContinueWith(responseTask =>
                            {                                    
                            });                                
                        }                            
                        catch (Exception ex)
                        {
                            using (var stw = new StreamWriter(path + "error.txt", true))
                            {
                                stw.WriteLine("Error with Update cURL Call - " + ex.ToString() + "\r\n---------------------------------------------------");
                            }
                            result = "Error with Update cURL Call - " + ex.ToString();
                        }

                        try
                        {                                
                            file = System.IO.File.ReadAllText(path + "saveActivate.xml");                                
                            response = new HttpRequestMessage(HttpMethod.Post, 'Web Extension 4.1' + id + 'Web Extension 4.1');                                
                            response.Content = new StringContent(file, Encoding.UTF8, "application/xml");

                            await client.SendAsync(response).ContinueWith(responseTask =>
                            {                                    
                            });                                
                        }                            
                        catch (Exception ex)
                        {
                            using (var stw = new StreamWriter(path + "error.txt", true))
                            {
                                stw.WriteLine("Error with Save and Activate cURL Call - " + ex.ToString() + "\r\n---------------------------------------------------");
                            }
                            result = "Error with Save and Activate cURL Call - " + ex.ToString();
                        }

                        try
                        {                                
                            response = new HttpRequestMessage(HttpMethod.Get, 'Web Extension 5.1' + id + 'Web Extension 5.2');                                
                            await client.SendAsync(response).ContinueWith(responseTask =>
                            {                                                                       
                                result = "Value update was a success!";                                    
                            });                                
                        }                            
                        catch (Exception ex)
                        {
                            using (var stw = new StreamWriter(path + "error.txt", true))
                            {
                                stw.WriteLine("Error with Load Config cURL Call - " + ex.ToString() + "\r\n---------------------------------------------------");
                            }
                            result = "Error with Load Config cURL Call - " + ex.ToString();
                        }
                    }                        
                }
                else
                {
                    using (var tsw = new StreamWriter(path + "error.txt", true))
                    {
                        tsw.WriteLine("Error getting current SDM ID number.\r\n---------------------------------------------------");
                    }
                    result = "Error getting current SDM ID number.";
                }
            }
}

这是 Update() 函数的更新代码。

最佳答案

更改您的异步方法以返回一个任务,然后在您的主方法调用中等待(您的异步方法):

public async Task<T> Update(List<string> allNumbers, List<string> allValues)

在主要方法中

await Update(allNumbers, allValues);

关于c# - 在调用异步函数后执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51141985/

相关文章:

c# - 在UWP 应用程序中,我可以在建立连接后获取SSL 证书错误列表吗?

c# - DataGridViewColumn 的进度条

c# - 将大文件上传到 Azure 数据库会出现错误(ASP.NET 网站)

c# - 仅由我的网站调用 Web Api

node.js - 等待异步方法完成

C# 将 UTC int 转换为 DateTime 对象

c# - C# 中的多维数组列表或列表?

css - 如何设置水平列表垂直li ul

asynchronous - Kotlin 中的延迟函数内部是如何工作的?

c# - 从异步编程模型 (APM) 转向基于任务的异步模式 (TAP)