Is there an efficient way to download a file and save it on disk in a "background" way without blocking the current execution of an action in a mvc controller?
Currently I have the following example code working:
public ActionResult Index()
{
InitiateDownload();
var model = GetModel();
return View(model);
}
private void InitiateDownload()
{
Task.Run(() => DownloadAndSaveFileAsync()).ConfigureAwait(false);
}
private async Task DownloadAndSaveFileAsync()
{
var response = await GetResponse();
using (var fileStream = new FileStream("c:\\file.zip", FileMode.Create, FileAccess.Write, FileShare.None))
{
await response.Content.CopyToAsync(fileStream).ConfigureAwait(false);
}
}
public async Task<HttpResponseMessage> GetResponse()
{
var client = new HttpClient();
client.BaseAddress = new Uri("http://someUrl.com");
return await client.GetAsync("someResourceEndPoint").ConfigureAwait(false);
}
I have read several places that you should not use Task.Run on the server (in the worker thread) so I was wondering if this example is scaleable (eg. if it receives 10 requests every second) or reliable or if there are any appropriate way to make it so?
Thanks