C# 调用web API时异步/等待不起作用
大家好,我有一个异步Web API,我想当我点击一个按钮执行它时,剩下的过程将不会继续,直到API返回结果,下面是我的APIC# 调用web API时异步/等待不起作用,c#,api,asynchronous,async-await,C#,Api,Asynchronous,Async Await,大家好,我有一个异步Web API,我想当我点击一个按钮执行它时,剩下的过程将不会继续,直到API返回结果,下面是我的API btnSubmit.Click += async (sender, e) => { var jobId = txtJobID.Text; if (txtJobID.Text.Length <= 0) { txtJobID.RequestFocus(); t
btnSubmit.Click += async (sender, e) =>
{
var jobId = txtJobID.Text;
if (txtJobID.Text.Length <= 0)
{
txtJobID.RequestFocus();
txtJobID.SetError("Job ID required", iconError);
}
else
{
var request = HttpWebRequest.Create(string.Format("http://192.168.79.174:90/api/test/" + jobId));
request.ContentType = "application/json";
request.Method = "GET";
using (HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var content = reader.ReadToEnd();
dynamic arr = JsonConvert.DeserializeObject(content);
foreach (dynamic obj in arr)
{
tvJobID.Text = obj.JobID;
tvJobType.Text = obj.JobType;
tvDueDate.Text = obj.DueDate;
tvVisitTime.Text = obj.Time;
tvVisitStatus.Text = obj.VisitStatus;
tvAddress1.Text = obj.Address1;
tvAddress2.Text = obj.Address2;
tvPostCode.Text = obj.PostCode;
tvAuthority.Text = obj.Authority;
}
if (content == null || content == "" || content == "[]")
{
//Console.Out.WriteLine("Response contained empty body...");
Toast.MakeText(ApplicationContext, "Invalid Job ID or no visits for this ID. Please try again", ToastLength.Long).Show();
}
else
{
layoutController.Visibility = ViewStates.Visible;
}
}
}
}
};
btnSubmit.Click+=async(发送方,e)=>
{
var jobId=txtJobID.Text;
如果(txtJobID.Text.Length相当长的一段时间是多长?您期望的时间范围是什么?您是否分析了web服务以找到任何瓶颈(如果应该存在的话)?为什么使用动态
?在运行时之前您似乎不太可能真正知道web服务将返回的对象类型。@jst将应用程序冻结7-8秒onds。我看不到任何瓶颈,我想我在错误的地方使用了async/await。我可以在其他地方使用await吗。很抱歉,我对此了解很少。感谢不要使用HttpWebRequest
使用HttpClient
。它有一个非常易于使用的async
api。