如何在 C# 中 for 循环的每次迭代之间添加一些延迟? [英] How to add some delay between each iteration of for loop in C#?

查看:33
本文介绍了如何在 C# 中 for 循环的每次迭代之间添加一些延迟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 C# 开发 ASP.NET MVC3.我想在 for 循环的每次迭代之间添加一些延迟.

I'm working on ASP.NET MVC3 with C#. I want to add some delay between each iteration of for loop.

for(int i=0; i<5; i++)
{
    //some code
    //add delay here
}

那么我该怎么做呢?

推荐答案

正如其他答案所说,使用 Thread.Sleep 将使线程休眠...但鉴于您正在编写网络应用程序,我不认为它会做你想做的.

As other answers have said, using Thread.Sleep will make a thread sleep... but given that you're writing a web app, I don't think it'll do what you want it to.

如果目标是让用户一次看到发生的事情,那么您需要将延迟放在客户端.如果您在发送 HTTP 响应之前有五个一秒的延迟,那仅意味着用户必须等待五秒钟才能看到您的结果页面.

If the aim is for users to see things happening one second at a time, you'll need to put the delay on the client side. If you have five one-second delays before you send an HTTP response, that just means the user will have to wait five seconds before they see your result page.

听起来你应该用 AJAX 来做这件事.

It sounds like you should be doing this with AJAX.

如评论中所述,您可能值得查看 window.setTimeout Javascript 调用.(我不会做"Javascript,所以恐怕我无法帮助解决任何相关细节.)

As noted in comments, it's probably worth you looking at the window.setTimeout Javascript call. (I don't "do" Javascript, so I'm afraid I won't be able to help with any of the details around that.)

这篇关于如何在 C# 中 for 循环的每次迭代之间添加一些延迟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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