[英]ASP.NET C# Posting to API and await Status in parallel
我正在尝试提出一种正确的体系结构,在该体系结构中,我可以发送大量API帖子来请求车队中车辆的GPS位置。 目的是发出10多个状态请求,然后让每个线程等待响应,然后将结果插入数据库表。 请求和响应是Json。 我让代码同步工作,一次一次,每辆车可能需要2分钟。 我的代码是:
客户端JavaScript计时器触发提交btnGetData_Click
btnGetData_Click调用DoVehicleGetStatus():
public static async Task DoVehiclePollStatus()
int vehicleInfoId;
string vehicleVIN;
string vehicleMileage;
string tokenId;
// Build DataSet with list of vehicle information needed to log in.
// Loop thru each Vehicle.
int iCount = ds.Tables[0].Rows.Count;
foreach (DataRow dr in ds.Tables[0].Rows)
{
vehicleInfoId = Convert.ToInt32(dr["Id"]);
vehicleVIN = dr["VehicleVIN"].ToString();
vehicleMileage = dr["VehicleListMileage"].ToString();
tokenId = dr["VehicleListToken"].ToString();
// Serialize LoginInfo to Json
DataClass.GetStatusRequestBodyStruct getFromVehicle = new DataClass.GetStatusRequestBodyStruct();
getFromVehicle.getFromVehicle = true;
string requestJsonMessage = new JavaScriptSerializer().Serialize(getFromVehicle);
DataClass.GetVehicleStatusStruct vs = new DataClass.GetVehicleStatusStruct();
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type","application/json");
StringContent httpContent = new StringContent(requestJsonMessage);
// Set Header Parameters
try
{
httpContent.Headers.TryAddWithoutValidation("tokenId", tokenId);
httpContent.Headers.TryAddWithoutValidation("VIN", vehicleVIN);
HttpResponseMessage response = await httpClient.PostAsync(new Uri(DataClass.API_URIGetVehicleStatus), httpContent);
}
catch (Exception ex)
{
errorMessage = ex.Message;
}
....
..save response (string) data in database...
在点击await httpClient.PostAsync之后,程序将返回执行结果,而我从请求帖子中都没有得到响应。 如果此设计不正确,可以请您提出一种更好的方法。
根据您得到的错误,应将public static async void DoVehiclePollStatus()
更改为public static async Task DoVehiclePollStatus()
。 不建议使用异步无效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.