Reputation: 383
I need to save file in two different server using .net api.Its asp.net Core web api. I want to return the response to the caller when saving the file in any of the server is succeeded. Could this be achieved using async programming? Can we return the response from api and let it save at other location?
For now I am using Parallel option:
var imageName = $"{Guid.NewGuid().ToString()}.{extension}";
var locations = new ConcurrentDictionary<string, string>();
Parallel.ForEach(destinationFolders, folder =>
{
try
{
var fullName = $@"{folder.Value}\{imageName}";
if (!Directory.Exists(folder.Value))
Directory.CreateDirectory(folder.Value);
var bytes = Convert.FromBase64String(content);
using (var imageFile = new FileStream(fullName, FileMode.Create))
{
imageFile.Write(bytes, 0, bytes.Length);
imageFile.Flush();
}
locations.TryAdd(folder.Key, Regex.Replace(folder.Value, @"\\", @"\"));
}
catch (Exception ex)
{
Logging.Log.Error($"{Constants.ExceptionOccurred} : {ex.Message} against {folder.Key} Value : {Regex.Replace(folder.Value, @"\\", @"\")}");
}
});
However the problem here is I am making it to wait while it finishes saving in both the location and return the response.
Upvotes: 1
Views: 78
Reputation: 1973
You do not appear to need Task Parallel for this. Consider the following truly asynchronous approach. Also note, you only need to do the Base64 decode once.
public Task WriteFiles(IEnumerable<string> destinationFolders, string content)
{
byte[] bytes = Convert.FromBase64String(content);
IList<Task> tasks = new List<Task>();
foreach (var folder in destinationFolders)
{
// <snipped>
Func<Task> taskFactory = async () =>
{
using (var imageFile = new FileStream(fullName, FileMode.Create))
{
await imageFile.WriteAsync(bytes, 0, bytes.Length);
await imageFile.FlushAsync();
}
};
tasks.Add(taskFactory());
// <snipped>
}
return Task.WhenAny(tasks);
}
Upvotes: 2