如何将 HTTP 响应延迟 x 秒?
我不会详细解释为什么我需要这个,它是内部分析包的一部分,但我的目标是创建一个 2 秒后返回重定向的 ASP.NET 页面。
我看到的问题是使用 Thread.Sleep(2000); 会占用我的 ASP.NET ThreadPool 线程之一。据我了解,这是相当浪费的,因为线程创建并不便宜,而且我需要该服务器来处理尽可能多的并发连接。
那么,让 HTTP GET 在至少 2 秒后返回我的页面的最佳方法是什么(超过 2 秒没问题,只是不能低于)。
protected void Page_Load(object sender, EventArgs e)
{
Thread.Sleep(2000);
Response.Redirect(RedirectUri);
}
编辑
我应该澄清一下,请求的页面实际上是作为图像请求的,因此不可能返回 HTML。它将像这样使用:
<img src="http://hostname/record.aspx"/>
重定向到实际图像应该需要 2 秒。
I won't go into the boring details of why I need this, it's part of an internal analytics package, but my goal is to create an ASP.NET page that returns a redirect after 2 seconds.
The problem I'm seeing is that using Thread.Sleep(2000);
is going to hold up one of my ASP.NET ThreadPool threads. As I understand it, this is pretty wasteful as thread creation isn't cheap and I need this server to handle as many possible simultaneous connections as possible.
So, what's the best way to have HTTP GETs to my page return after at least 2 seconds (over 2 seconds is no problem, it just can't be under).
protected void Page_Load(object sender, EventArgs e)
{
Thread.Sleep(2000);
Response.Redirect(RedirectUri);
}
EDIT
I should clarify, the requested page is actually requested as an image, so returning HTML isn't possible. It'll be used like so:
<img src="http://hostname/record.aspx"/>
The redirect to an actual image should take 2 seconds.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以实现
IHttpAsyncHandler
。请参阅 MSDN。You could implement
IHttpAsyncHandler
. See MSDN.用JS来做:
Do it in JS:
没有简单的方法可以在不占用线程的情况下延迟程序执行。理论上,您可以在发生重定向的另一台服务器上设置延迟,但如果您只是试图在重定向之前造成延迟或超时,则必须付出等待线程的代价。
There is no way simple way to delay program execution without holding up a thread. You could in theory set up a a delay at the other server where the Re-Direct is occurring, but if you are just trying to cause a delay or timeout prior to the Redirect, you'll have to pay the penalty of a waiting thread.
您可以在标记本身上执行此操作,您可以放置如下内容:
You can do this on the markup itself, you can put something like: