0
\$\begingroup\$

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);
    }
}
\$\endgroup\$
2
  • 2
    \$\begingroup\$ Welcome to Code Review! Please edit your question so that the title describes the purpose of the code, rather than its mechanism. We really need to understand the motivational context to give good reviews. Thanks! \$\endgroup\$ Commented Nov 14, 2019 at 9:34
  • 1
    \$\begingroup\$ You are using Path.Combine which is great, but then you hardcode the path delimiter \\. The Images and Source names should be their own distinct parameters. \$\endgroup\$
    – Brad M
    Commented Nov 14, 2019 at 16:07

1 Answer 1

2
\$\begingroup\$

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);

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.