I have the follwing code :
List<Task<Response>> tasks = new List<Task<Response>>();
foreach (string url in urls)
{
Task<Response> task = AsyncRequest(url);
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray());
Where Response is a simple class with 2 members :
public class Response {
public bool isError;
public string content;
}
And the task is the following:
public async Task<Response> AsyncRequest(string url) {
Task<HttpResponseMessage> getTask = httpClient.GetAsync(url);
HttpResponseMessage message;
try
{
message = await getTask;
}
catch (Exception e)
{
Debug.LogFormat("GET request error for URL {0}: {1}", url, e);
return null;
}
Response response = new Response
{
isError = !message.IsSuccessStatusCode,
content = await message.Content.ReadAsStringAsync()
};
return response;
}
When the code is executed, Unity freezes on the line tasks.Add(task)
.
In my original code, the task was stored with a key in a Dictionary<string, Task<Response>>
, and it ended up the same way with a freeze of Unity.
If I create a list of tasks without result like List<Task> tasks
, the freezing behaviour doesn’t happen anymore when adding elements to the list but when the line Task.WaitAll(tasks)
is reached.
Finally, I found out that using an array Task<Response>[] tasks
does the same thing as above and freezes at Task.WaitAll(tasks)
too.
My question is why does Unity crashes here ? What are the option I have to solve this issue ?