0

On loading app I need to download 3 small json file less than 200kb. I have 3 methods like this :

private static async Task<bool> DownloadOne()
    {
        using (var tokSource = new CancellationTokenSource(5000))
        {
            try
            {
                _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var zurl = "URL");
                var response = await _httpClient.GetAsync(zurl, tokSource.Token);
                using (var stream = await response.Content.ReadAsStreamAsync())
                {
                    ar localFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData);
                    var newpath = Path.Combine(localFolder, "one.json");
                    var fileInfo = new FileInfo(newpath);
                    using (var fileStream = fileInfo.OpenWrite())
                    {
                        await stream.CopyToAsync(fileStream);
                    }
                }
            }
            catch (OperationCanceledException)
            {
                return false;
            }
            catch (Exception e)
            {
                return false;
            }               
        }
        return true;
    }

Is it more fast method simultaneous than doing ?

await DownloadOne();
await DownloadTwo();
await DownloadThr();
MultiValidation
  • 823
  • 7
  • 21
  • What have you tried to do to measure this? – Trevor Sep 12 '20 at 20:03
  • What do you mean by simultaneous? Can you show an example? – MultiValidation Sep 12 '20 at 20:06
  • meaning maybe it s better to not wait first download was finish before strat second one – MilkaMilka Sep 12 '20 at 20:08
  • 1
    rather than ask us, it seems like it would be pretty simple to measure and compare the results of the two approaches – Jason Sep 12 '20 at 20:16
  • @MilkaMilka "Your" code, device, network, server, etc... will all effect "your" outcome, so test and measure it yourself for your use-case/environment : https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/how-to-use-parallel-invoke-to-execute-parallel-operations – SushiHangover Sep 12 '20 at 20:25
  • 1
    @SushiHangover thanks, sound great. As it s just small file i don't think it will affect network with 3 GET of 100 or 200ko – MilkaMilka Sep 12 '20 at 20:39

1 Answers1

0

Yes, there is. You are waiting for each file to be downloaded before starting to download the next file. You can instead run all in parallel and wait for them to finish with Task.WhenAll():

var tasks = new Task[]{DownloadOne(), DownloadTwo(), DownloadThr()};
await Task.WhenAll(tasks);
Dzliera
  • 646
  • 5
  • 15
  • yeah that s what i'm just looking and test Task.WhenAll :) have tested and seam working good but not tested in mobile with xamarin – MilkaMilka Sep 12 '20 at 21:39