1
昨天我已經found out如何在沒有異步/等待的情況下創建多個異步http請求。但是今天我需要在循環中完成它:如果某些響應不滿足某些條件 - 我需要爲它們更改請求並再次發送這些請求。它可能會重複多次。 我試過這段代碼:如何在循環中創建異步http請求?
do
{
var loadingCoordinatesTasks = new List<Task<Terminal>>();
var totalCountOfTerminals = terminalPresetNode.ChildNodes.Count;
var uiTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
foreach (var terminal in terminals.Except(_terminalsWithCoordinates))
{
var address = terminal.GetNextAddress();
var webRequest = (HttpWebRequest)WebRequest.Create(GeoCoder.GeoCodeUrl + address);
var webRequestTask = Task.Factory.FromAsync<WebResponse>(webRequest.BeginGetResponse,
webRequest.EndGetResponse,
terminal);
var parsingTask = webRequestTask.ContinueWith(antecedent =>
{
// Parse the response
});
loadingCoordinatesTasks.Add(parsingTask);
}
Task.Factory.ContinueWhenAll(loadingCoordinatesTasks.ToArray(), antecedents =>
{
foreach (var antecedent in antecedents)
{
var terminalWithCoordinates = antecedent.Result;
if (antecedent.Status == TaskStatus.RanToCompletion &&
!terminalWithCoordinates.Coordinates.AreUnknown)
{
_terminalsWithCoordinates.Add(terminalWithCoordinates);
_countOfProcessedTerminals++;
}
}
});
} while (_countOfProcessedTerminals < totalCountOfTerminals);
,但它可以檢查在while
只是條件後執行的每一個組請求?
謝謝!看看我的編輯 – Zharro
不,它不是線程安全的,但我可以做到這一點。問題是:如何組織循環? 如果要寫'while(true)',它會產生很多額外的請求。 – Zharro