Web API-异步模块或处理程序已完成,而异步操作仍处于挂起状态
本文关键字:异步操作 挂起状态 已完成 异步 API- 模块 程序 处理 Web | 更新日期: 2023-09-27 18:25:15
无法理解这一点。想法?
[控制器]
await _imageRepo.Resize(name, width, height, queryParams, (image) =>
{
response = createResponse(image);
});
[储存库]
public async Task Resize(string name, string width, string height, ImageOptions options, Action<Images> callback)
{
var actionName = "resized";
var newWidth = Convert.ToInt32(width);
var newHeight = string.IsNullOrEmpty(height) ? newWidth : Convert.ToInt32(height);
var resizedName = ApplyOptionName(string.Format("{0}-{3}-{1}x{2}", name, newWidth, newHeight, actionName), options);
await Get(resizedName, null, async (previousImage) =>
{
if (previousImage != null)
{
callback(previousImage);
return;
}
await Get(name, null, image =>
{
if (image == null)
{
callback(null);
return;
}
using (ImageFactory imageFactory = new ImageFactory())
{
imageFactory.Load(image.ToStream());
imageFactory.Resize(new ResizeLayer(new Size(newWidth, newHeight), ResizeMode.Max, AnchorPosition.Left));
ProcessImageOptions(imageFactory, options);
using (MemoryStream ms = new MemoryStream())
{
imageFactory.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
var newImage = Create(new Images(ms) { Name = resizedName });
callback(newImage);
}
}
});
});
}
【例外】
[InvalidOperationException: An asynchronous module or handler completed while an asynchronous operation was still pending.]
所有这些回调都让我感到不舒服,但为什么我会犯这个错误?
虽然回调并不好。我们决定继续使用这种模式。这意味着要弄清楚如何使这些lambda的返回任务。
这很容易。
正如Stephen Cleary所写"将它们更改为Func<…,任务>…"。
这就是最终的实施。
public async Task Resize(string name, string width, string height, ImageOptions options, Func<Images, Task> callback)
{
var actionName = "resized";
var newWidth = Convert.ToInt32(width);
var newHeight = string.IsNullOrEmpty(height) ? newWidth : Convert.ToInt32(height);
var resizedName = ApplyOptionName(string.Format("{0}-{3}-{1}x{2}", name, newWidth, newHeight, actionName), options);
await Get(resizedName, null, async (previousImage) =>
{
Images resizedImage = null;
if (previousImage != null)
{
resizedImage = previousImage;
}
else
{
await Get(name, null, async (image) =>
{
if (image == null)
{
resizedImage = null;
return;
}
using (ImageFactory imageFactory = new ImageFactory())
{
imageFactory.Load(image.ToStream());
imageFactory.Resize(new ResizeLayer(new Size(newWidth, newHeight), ResizeMode.Max, AnchorPosition.Left));
ProcessImageOptions(imageFactory, options);
using (MemoryStream ms = new MemoryStream())
{
imageFactory.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
resizedImage = await CreateAsync(new Images(ms) { Name = resizedName });
}
}
});
}
await callback(resizedImage);
});
}
一个次要的因素。。。但没有造成任何伤害。
谢谢你的帮助!