Is it bad practice to mix async and sync call in same ASP.NET core API call?
For example, in following code method CropBlackBroderOfAnImageAsync
is an async method.
On the other hand SaveImageForProcessing(file, sourceFolderPath);
is a sync method.
The reason I am calling SaveImageForProcessing
synchronously is
that I want use the result of it to execute the code in CropBlackBroderOfAnImageAsync
.
public async Task<(string sourceFolderPath, string destinationFolderPath)> CropBlackBorderOfAnImage(IFormFile file)
{
var extension = Path.GetExtension(file.FileName);
var newFileName = Guid.NewGuid().ToString();//Create a new Name for the file due to security reasons.
var fileNameSource = newFileName + extension;
var sourceFolderPath = Path.Combine(Directory.GetCurrentDirectory(), "Images\\Source", fileNameSource);
var fileNameDestination = newFileName + "Result" + extension;
var destinationFolderPath = Path.Combine(Directory.GetCurrentDirectory(), "Images\\Destination", fileNameDestination);
SaveImageForProcessing(file, sourceFolderPath);
await _imageCropBlackBroderService.CropBlackBroderOfAnImageAsync(sourceFolderPath, destinationFolderPath);
return (sourceFolderPath, destinationFolderPath);
}
private void SaveImageForProcessing(IFormFile file, string path)
{
using (var bits = new FileStream(path, FileMode.Create))
{
file.CopyTo(bits);
}
}
1 Answer 1
Well, generally it is not a problem to call a sync method within async method.
You are actualy doing this in more then few instances (GetExtension, NewGuild, ToString, etc...)
But if you have an async method available it would be shame to not use it.
Which you have - IFormFile.CopyToAsync()
.
using (var bits = new FileStream(path, FileMode.Create))
{
await file.CopyToAsync(bits);
}
await _imageCropBlackBroderService.CropBlackBroderOfAnImageAsync(sourceFolderPath, destinationFolderPath);
Explore related questions
See similar questions with these tags.
Path.Combine
which is great, but then you hardcode the path delimiter\\
. TheImages
andSource
names should be their own distinct parameters. \$\endgroup\$