Unity - Async/Await too slow

Viewed 789

I'm downloading a texture from a server. Running the code in the editor takes a few second to download it. But when I build it and run the .exe the download takes multiple minutes. Is there a reason for it? Any build option?

HttpWebRequest request = WebRequest.CreateHttp(PATH);
WebResponse response = await request.GetResponseAsync();
Stream stream = response.GetResponseStream();

byte[] data = new byte[response.ContentLength];

int bytesRead = 0, count = (int)response.ContentLength;
while (bytesRead < count) {
    int read = await stream.ReadAsync(data, bytesRead, count - bytesRead);

    if (read <= 0)
        continue;

    bytesRead += read;
}

EDIT:
The Problem is awaiting. Awaiting Stream.Read called in Task.Factory.StartNew results in the same behavior. Values from Task Manager Ethernet Profiling:

Async: Editor: 47Mbps; Build 4.4Mbps
Sync: Editor = Build: 61Mbps

1 Answers

Okay, the problem is, that async/await does not work the way it 'usually' works. After reading this article I changed the code and it works fine. Async/Await in Unity actually works more or less the same as the coroutines do. So awaiting an async method waits for a minimum of one frame. That's where this 16ms execution time comes from (1s / 60FPS = 16ms). So wrapping the download code in a task, changing ReadyAsync to Read, and only awaiting this task solved the problem. Now I have 61Mbps and async download.

Related