How is it better to organize an asynchronous code with a request in a loop, put the loop into a separate method and call it asynchronously from the main thread or leave the loop in the main thread, and just make the request asynchronous?
- fiveWell, async / await is usually better. But so that we do not guess what is in the black box, show your code. - VladD
- There is no code yet, that's why I want to figure it out first! - Borz Torkoy
- Well, for the time being, your question looks something like this: “I'm going to write two pieces of code, which one is better?” The correct answer: “How do we know?” - VladD
- Where and why do you have a cycle? - Monk
- I load the list of users from the site, in order to get the full list I need to consistently make multiple requests in a cycle, in response I get portions of users, from which one file is collected. I want to run this file generation separately from the main thread so that the interface continues to be active. - Borz Torkoy
|
1 answer
If you just make requests to the site, and write the result to a file, it makes sense not to bother with multithreading, but to use asynchronous functions. You should have something like this:
async Task ReadAndWrite() { var http = new HttpClient(); using (var outStream = File.Create(path)) { for (int i = 0; i < 100; i++) { var uri = string.Format(uriPattern, i); string s = await GetPartInformation(http, i); var info = ExtractInfo(s); byte[] bytes = ConverToBytes(info); await stream.WriteAsync(bytes, 0, bytes.Length); } } } const string uriPattern = "http://example.org/get/{0}"; async Task<string> GetPartInformation(HttpClient http, int i) { var uri = string.Format(uriPattern, i); byte[] information; using (var response = await httpClient.GetAsync(uri)) { response.EnsureSuccessStatusCode(); using (var content = response.Content) return await content.ReadAsStringAsync(); } } This code can be improved. For example, a simple improvement - do not wait for the end of the recording, and proceed to further reading.
async Task ReadAndWrite() { Task pendingWriteTask = null; var http = new HttpClient(); using (var outStream = File.Create(path)) { for (int i = 0; i < 100; i++) { var uri = string.Format(uriPattern, i); string s = await GetPartInformation(http, i); var info = ExtractInfo(s); byte[] bytes = ConvertToBytes(info); if (pendingWriteTask != null) await pendingWriteTask; pendingWriteTask = stream.WriteAsync(bytes, 0, bytes.Length); } if (pendingWriteTask != null) await pendingWriteTask; } } If the ExtractInfo and ConvertToBytes slow, it should be unloaded from the UI stream using var info = await Task.Run(() => ExtractInfo(s)); etc.
- This wanted to find out. Thanks - Borz Torkoy
- @BorzTorkoy: Please! Hope will help. - VladD
|