簡體   English   中英

ASP.NET C#並行發布到API並等待狀態

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM