I try to write app which takes a bunch of URLs and asynchronously saves theirs content in separated files. I wrote that code as synchronous and it worked quite okay so I tried to make it async. The problem is that I get some exceptions: The process cannot access the file because it is being used by another process. I don't know much about streams but is it possible that 2 threads share the same stream and temporarily close "their" files but not fully and that's why I've got that error? If not, what can it be?
public override async Task ExecuteCommandAsync(IEnumerable<string> urls)
{
string directory = "some directory";
int i = 0;
foreach (var url in urls)
{
tasks.Add(Task.Run(async () =>
{
try
{
await DownloadJsonFromUrl(url, directory, i);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}));
i++;
Console.WriteLine($"task nr {i} started.");
}
await Task.WhenAll(tasks);
private async Task DownloadJsonFromUrl(string url, string directory, int fileNumber)
{
using (var httpClient = _clientFactory.CreateClient())
using (var response = await httpClient.GetAsync(url,
HttpCompletionOption.ResponseHeadersRead))
using (FileStream fileStream = File.Open(directory + fileNumber.ToString() + ".json",
FileMode.Create, FileAccess.Write, FileShare.None))
using (var clientStream = await response.Content.ReadAsStreamAsync())
{
await clientStream.CopyToAsync(fileStream);
}
}