How to add some delay between each iteration of for loop in C#?

前端 未结 6 1503
轻奢々
轻奢々 2020-12-22 11:32

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 dela         


        
相关标签:
6条回答
  • 2020-12-22 12:03

    You can use something like a one-second delay:

    System.Threading.Thread.Sleep (1000);
    

    though make sure this is only for debugging purposes. There's little more annoying than intentionally slowing down software.

    Other than an easy way to introduce performance improvements later, of course :-)

    0 讨论(0)
  • 2020-12-22 12:09

    Another approach then the ones already described may be Reactive Extensions (Rx). There are some methods in there that generate sequences of values in time. In your case, you could use the following code.

    var values = Observable.Generate(
            0,           // Initializer.
            i => i < 5,  // Condition.
            i => i + 1,  // Iteration.
            i => i,      // Result selector.
            i => TimeSpan.FromSeconds(1));
    var task = values
        .Do(i => { /* Perform action every second. */ })
        .ToTask();
    values.Wait();
    

    The ToTask call allows you to wait for the IObservable to complete. If you don't need this, you can just leave it out. Observable.Generate generates a sequence of values at specific timestamps.

    0 讨论(0)
  • 2020-12-22 12:10

    The simplest way is to put the current thread to sleep.

    System.Threading.Thread.Sleep (200);
    

    Remember though, that threads in a web application are very precious resources, and putting one to sleep still keeps the thread busy.

    There is usually no good reason to do this in a web application.
    Whatever problem needs you to do this, can be solved in a better manner.

    0 讨论(0)
  • 2020-12-22 12:12

    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.

    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.

    It sounds like you should be doing this with AJAX.

    EDIT: 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.)

    0 讨论(0)
  • 2020-12-22 12:19

    you can use Thread.Sleep();

    int milliseconds = 5000;
    Thread.Sleep(milliseconds);
    

    this stops the execution of the current thread for 5 seconds.

    0 讨论(0)
  • 2020-12-22 12:29

    How about something like

    System.Threading.Thread.Sleep(1000);
    

    Thread.Sleep Method (Int32)

    0 讨论(0)
提交回复
热议问题