Time delay in For loop in c#

前端 未结 7 1321
伪装坚强ぢ
伪装坚强ぢ 2020-12-06 01:18

how can i use a time delay in a loop after certain rotation? Suppose:

for(int i = 0 ; i<64;i++)
{
........
}

i want 1 sec delay after ea

7条回答
  •  既然无缘
    2020-12-06 02:04

    Try this simpler version without dependency on async or await or TPL.

    1. Spawns 50 method calls ,
    2. sleeps for 20 secs,
    3. checks it 20 or x items are complete.
    4. if not sleeps again for 20 secs
    5. if yes resumes loop

    Code here

     foreach (var item in collection)
                {
                    if (cnt < 50)
                    {
                        cnt++;
                        DoWork(item);
                    }
                    else
                    {
                        bool stayinLoop = true;
                        while (stayinLoop)
                        {
                            Thread.Sleep(20000);
                            if (cnt < 30)
                            {
                                stayinLoop = false;
                                DoWork(item);
                            }
                        }
                    }
                }
    

    Do work in a separate thread, so that sleep doesn't block you, could be a background worker , Begin , End method of webrequest or optionally an async task or Task.Run()

    function DoWork()
    //Do work in a sep thread.
    cnt--;
    )
    

提交回复
热议问题