I am executing a set of HTTP API commands on our embedded platform but need to add delays to ensure that the eventual GPIO operations are timed properly. I've followed a couple of examples from StackOverflow and Microsoft , but continue to have weird behavior.
I read a set of XML commands in to a list of Actions.
<action url="http://10.10.5.112/api/analogoutputs/0/3" delay="0"/>
<action url="http://10.10.5.112/api/analogoutputs/1/6" delay="5" />
<action url="http://10.10.5.112/api/analogoutputs/2/9" delay="10" />
<action url="http://10.10.5.112/api/analogoutputs/3/12" delay="15" />
Once read, the processing program initiates a set of calls to the ProcessHttpCallWithDelay method using Task.WhenAll:
IEnumerable<Task<bool>> httpCalls =
from Action in LogicActions
select ProcessHttpCallWithDelay(Action.url, Action.delay);
// Make array of http calls
Task<bool>[] httpCallsArray = httpCalls.ToArray();
// Await the completion of all of the http calls
bool[] results = await Task.WhenAll(httpCallsArray);
// Process results
... do something with results ..
HTTP API processing method:
private async Task<bool> ProcessHttpCallWithDelay(string url, int delay)
{
bool ok = true;
try
{
await Task.Delay(delay*1000);
WebRequest request = WebRequest.Create(url);
request.ContentType = "application/json";
HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();
string returnString = response.StatusCode.ToString();
response.Close();
}
catch (Exception ex)
{
ok = false;
}
return ok;
}
The problem is that the await Task.WhenAll(httpCallsArray) doesn't appear to await for all tasks to complete and moves on to the processing steps and no HTTP command is actually sent.
If I do a Task.WhenAll(httpCalls), using the IEnumerable, I do get one http command to be executed, but still the await for all tasks doesn't wait and moves to the processing step.
I would have expected in both cases to wait for all the WebResponses and returns from the ProcessHttpCallWithDelay method to finish. Can someone help me understand what might be going here?