请求完成后的处理 [英] Processing after the request was completed

查看:61
本文介绍了请求完成后的处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个API端点,需要尽快返回给调用者.当前返回时间不到1毫秒.但是,如果我将一些东西记录到数据库中,则现在需要将近10毫秒.

I have one API endpoint that needs to return to the caller as soon as possible. It currently returns under 1ms. If, however, I log some stuff to the database it now takes closer to 10ms.

您将如何处理请求的完成,然后在请求完成后进行某种处理?我尝试使用Response.Body.Flush(),但这并没有完成请求,仍然需要完整的10毫秒.看起来好像在发送/刷新有效负载,但是直到action方法完成,请求仍然没有完成.

How would you approach completing the request and then doing some kind of processing after the request was completed? I tried with Response.Body.Flush(), but that doesn't complete the request and it still takes the full 10ms. It looks like it's sending/flushing the payload, but the request still doesn't complete until the action method is completed.

在中间件中进行记录是否可行?

Would it work to do the logging in a middleware?

我发现的一种解决方法是像这样使用 FluentScheduler :

One workaround that I found was to use FluentScheduler like this:

JobManager.Initialize(new Registry());
JobManager.Start();

在host.Run()之前的Program.cs中,然后从这样的操作中计划立即任务:

in Program.cs before host.Run() and then schedule an immediate task from an action like this:

JobManager.AddJob(() =>
{
    // do something...
}, (s) => s.ToRunOnceIn(1).Seconds());

推荐答案

您需要以某种方式启动其他线程.放置在管道前面的中间件将使您有机会在请求完成之前进行工作.如果您从那里旋转一个线程,那么它可能会起作用.

You need to start somehow a different thread. A middleware put in front of the pipeline will give you the chance to do work just before the request completes. If you spin a thread, from there, then it might work.

您可能想使用某种生产者-消费者模式这样您就不会杀死服务器.否则,如果每个请求都启动了一个立即运行的线程,并且您同时有多个请求,则可能最终会耗尽资源.生产者-消费者将帮助您限制这项工作.

You probably want to use some sort of producer-consumer pattern so you don't kill your server. Otherwise, if every request starts a thread that does work immediately and you have many requests at the same time, you might end up running out of resources. A producer-consumer would help you throttle that work.

如果您不着急,可以等一周左右,等我交付ASP.NET的文件记录器,然后您会在此处看到类似的实现.

If you're not in a hurry, you can wait another week or so when I'll deliver the file logger for ASP.NET and then you'll see a similar implementation there.

这篇关于请求完成后的处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆