异步函数调用问题

时间:2016-06-21 14:19:50

标签: c# windows-phone-8

我正在开发Windows Phone应用程序。在调用以下函数时,执行此行后: HttpResponseMessage response = await client.GetAsync(connection1).ConfigureAwait(false);  它会跳过剩下的代码并控制转到父函数并执行其余代码并再次返回此函数。如何解决这个问题?

public async void vehicleValidation()    
{
    //isValidVehicle = true;
    var client = new System.Net.Http.HttpClient();
    //string connection = "http://mymlcp.co.in/mlcpapp/get_slot.php?vehiclenumber=KL07BQ973";
    string connection1 = string.Format("http://mymlcp.co.in/mlcpapp/?tag=GetIsValidUser&employeeId={0}&name={1}",txtVeh.Text,"abc");
    HttpResponseMessage response = await client.GetAsync(connection1).ConfigureAwait(false);
    //var response = await client.GetAsync(connection1);
   // HttpResponseMessage response = client.GetAsync(connection1).Result;
    var cont = await response.Content.ReadAsStringAsync();
    var floorObj = Newtonsoft.Json.Linq.JObject.Parse(cont);
    //var resp = await (new MLCPClient()).GetIsValidUser(txtVeh.Text, "xyz");

    if (String.IsNullOrEmpty(floorObj["error"].ToString()) || floorObj["error"].ToString().Equals("true"))
    {
        isValidVehicle = false;
    }
    else
    {

        isValidVehicle = true;
    }
}

1 个答案:

答案 0 :(得分:1)

除非你正在编写一个事件处理程序,否则你永远不应该有async void,你需要让你的函数在父函数中返回Task然后await函数。

阅读“Async/Await - Best Practices in Asynchronous Programming”,了解最佳做法,例如从不执行async void并让您的代码“一直异步”