gpt4 book ai didi

c# - OutputCache 序列化并发请求

转载 作者:太空宇宙 更新时间:2023-11-03 12:52:47 24 4
gpt4 key购买 nike

OutputCache is an easy way to improve performance在 ASP.NET <=4.6 MVC 中。我们应该将此属性应用于非常昂贵的操作,但在第一个请求和正在创建的缓存之间,我们可能会有很多并发请求 - 并且会消耗我们试图保护的服务器资源(内存、CPU、I/奥)。

如果多个请求来自同一个用户,默认aspnet serialize我们在此链接中看到的请求,The Downsides of ASP.NET Server Sate :

by default the ASP.NET pipeline will not process requests belonging to the same session concurrently. It serialises them, i.e. it queues them in the order that they were received so that they are processed serially rather than in parallel.

因此,为了模拟这种情况,我们需要创建多个请求(来自不同的用户)。这可以通过从多个浏览器创建请求或使用任何类型的多线程工作负载来完成。

因此,我尝试继承 OutputCacheAttribute 并创建类似 OutputCacheConcurrentRequestAttribute 的东西,并序列化来自多个用户的请求。有人试过吗?

想法是 Thread.Sleep 所有后续请求都在 OnActionExecuting 上对同一资源(考虑到 OutputCache 属性和操作的唯一性),而第一个请求不是完成。

查看 ILSpy 中的 IL,一些可以帮助我完成这项工作的方法是私有(private)的和内部的,例如:

程序集:System.Web.Mvc

命名空间:System.Web.Mvc

class OutputCacheAttribute
{
private GetChildActionUniqueId
private BuildUniqueIdFromActionParameters
}

internal class DescriptorUtil

我试图不重复代码并且不使用反射器(出于性能原因)。

有人遇到过同样的问题吗?


编辑 1

经过一些研究,我发现 MVC Donut caching继承 OutputCacheAttribute 和 they have rewritten it completely 面临很多困难:

In terms of implementing donut caching, hooking into the OutputCacheModule HttpModule would be very difficult/impossible, so instead we must rewrite the OutputCacheAttribute completely

使用 DonutOutputCacheAttribute 更容易完成我的想法。

最佳答案

您实际上是将此视为性能问题还是仅仅是理论上的?我要提醒的是,在这条路上走得太远会损害性能……也许考虑一种预热缓存的解决方案?

就是说,如果只锁定您尝试执行一次的操作,您的运气可能会更好。创建一个变量,并在操作过滤器中锁定该变量(在操作触发之前),并在操作触发后在您的操作过滤器中释放,这应该会序列化您的请求。

public class SerializedOutputCacheAttribute : OutputCacheAttribute
{
private readonly object lockObject = new object();

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
Monitor.Enter(this.lockObject);
base.OnActionExecuting(filterContext);
}

public override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
Monitor.Exit(this.lockObject);
}
}

然后您可以将它应用于任何 Action ,该 Action 将被序列化但不会影响其他 Action 。

    [SerializedOutputCache(Duration = 5000)]
public ActionResult About()

编辑: 这种方法行不通,因为 OutputCacheAttribute 实际上会推送到 IIS 进行缓存,因此该操作仍会触发多次。

关于c# - OutputCache 序列化并发请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34957060/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com