【发布时间】:2019-11-13 21:00:08
【问题描述】:
在同一个 asp.net 核心 api 调用中混合异步和同步调用是不好的做法
例如下面的代码
方法 CropBlackBroderOfAnImageAsync 是一个异步方法
另一方面 SaveImageForProcessing(file, sourceFolderPath);是同步方式
原因:我正在同步调用 SaveImageForProcessing,我想使用它的结果来执行 CropBlackBroderOfAnImageAsync 中的代码
完整的代码仓库
欢迎代码审查:https://github.com/aamir-poswal/ImageCropApp/
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);
}
}
【问题讨论】:
-
“原因”是没有意义的......但否则为什么你认为有任何问题?就像你打电话给
Path.GetExtension(file.FileName);没有问题,但你自己的方法似乎引起了关注......
标签: c# asynchronous asp.net-core .net-core