【问题标题】:Have code execute after call to async function调用异步函数后执行代码
【发布时间】:2018-07-02 18:36:08
【问题描述】:

我有一个异步 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() 函数的更新代码。

【问题讨论】:

  • 异步 void 函数不是一个好主意。如果有的话,您应该从异步方法返回一个 Task,然后在调用该方法之前使用关键字 Await。
  • 没有Update() 的任何代码,很难提供更多帮助。
  • 我认为 Update() 中执行 curl 调用的行现在可能就足够了。
  • 我没有看到你在哪里设置了 id 等于一个空字符串,然后你有一个if(id != "") 的 if 条件做你的 allNumbers 循环,所以难怪你只得到一个调用,然后返回。
  • 你有没有在这个方法里面设置断点?如果是这样,它是否会进入您的 for 循环,就像我之前所说的那样,您应该更改方法签名以返回 Task,然后在调用此异步方法的 main 方法中调用 Await。

标签: c# asp.net asynchronous curl httpclient


【解决方案1】:

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

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

在主方法中

await Update(allNumbers, allValues);

【讨论】:

  • @parrigin777 不客气。感谢您接受我的回答。
  • 你知道有没有办法让非异步方法调用异步方法?
  • @parrigin777 可以从非异步方法调用异步方法,但不能使用 await 关键字。
  • 我现在遇到的问题是我的异步方法返回一个 Task 并且我需要一个普通的字符串。这是可以实现的吗?我也尝试只调用该方法并让它更改全局字符串,但使用全局字符串的代码在异步方法更改全局字符串之前执行。
  • @parrigin777 可以使用返回的Task.Result获取返回的字符串值。例如,字符串 responseString = await YourAsyncMethod().Result;
猜你喜欢
  • 2015-07-19
  • 1970-01-01
  • 2018-01-12
  • 2013-02-02
  • 2017-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多