下面是同步资源筛选器
public class SimpleCacheSyncAttribute : Attribute, IResourceFilter
{
private Dictionary<PathString, IActionResult> CachedResponses = new Dictionary<PathString, IActionResult>();
public void OnResourceExecuting(ResourceExecutingContext context) {
PathString path = context.HttpContext.Request.Path;
if (CachedResponses.ContainsKey(path)) {
context.Result = CachedResponses[path];
CachedResponses.Remove(path);
}
}
public void OnResourceExecuted(ResourceExecutedContext context) {
CachedResponses.Add(context.HttpContext.Request.Path, context.Result);
}
}和一个版本的异步过滤器:
public class SimpleCacheAttribute : Attribute, IAsyncResourceFilter
{
private Dictionary<PathString, IActionResult> CachedResponses = new Dictionary<PathString, IActionResult>();
public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next) {
PathString path = context.HttpContext.Request.Path;
if (CachedResponses.ContainsKey(path)) {
context.Result = CachedResponses[path];
CachedResponses.Remove(path);
} else {
ResourceExecutedContext execContext = await next();
CachedResponses.Add(context.HttpContext.Request.Path, execContext.Result);
}
}
}我看不出使用异步筛选器有任何好处,因为对于同步筛选器,当OnResourceExecuting完成时,执行不会被阻塞,当响应返回到资源筛选器时,OnResourceExecuted会超时,所以超额工作流与异步筛选器相同,那么使用异步筛选器的好处是什么?
发布于 2020-12-10 22:28:48
使用异步过滤器有什么好处?
如果过滤时需要进行IO (输入/输出),例如:
查询database
简而言之,外部api、数据库服务器、文件系统都是在应用程序边界之外运行的外部进程。您的应用程序不需要在外部进程执行其工作时坐在那里等待。
一个简单的例子是打印机,当你向打印机发送一些东西时,你的计算机不会死机。当您的硬盘正在尝试查找文件时,您的应用程序不应该。
https://stackoverflow.com/questions/65234941
复制相似问题