如何限制C#foreach循环执行具有最大时间限制的迭代

时间:2016-01-15 01:15:41

标签: c# time foreach max limit

如何限制C#foreach循环,每次迭代应该正常运行,并且当前一次迭代花费超过30秒时,进行下一次迭代。

使用秒表,计时器......但是那些允许每30秒运行一次迭代,任何人都可以帮忙......

3 个答案:

答案 0 :(得分:0)

您必须为每次迭代生成一个单独的线程。但是感谢匿名代表,你几乎可以看到代码在本地执行。

foreach(var item in collection)
{
   var threadItem = item;
   ManualResetEvent mre = new ManualResetEvent(false);

   Thread workerThread = new Thread( () =>
       {
         try
            {
              // do something with threadItem in here
            }
        finally
            {
              mre.Set();
            }
       });

   workerThread.Start();
   mre.WaitOne(30000); // this will wait for up to 30 sec before proceeding to the next iteration.
   }

答案 1 :(得分:0)

或者你在这里有一个关于任务的例子。

foreach(var item in collection)
{
   int timeout = 30000;
   var task = Task.Run(()=>SomeOperationAsync());
   await Task.WhenAny(task, Task.Delay(timeout));
}

当然你也可以通过检查你的操作是否在30秒之前完成以及可能的结果来增强这一点。

答案 2 :(得分:-1)

只需使用一些线程:

   public static void ThreadAbortDemo(int sleeptime)
    {
        int[] collection = new int[10];
        foreach (var item in collection)
        {
            System.Threading.Thread thread = new System.Threading.Thread(() =>
            {
                try
                {
                    // do your stuff with item
                }
                catch (System.Threading.ThreadAbortException)
                {
                    // this thread is disposed by thread.Abort() statement
                    // do some stuff here before exit this thread
                }
            });
            thread.Start();
            System.Threading.Timer timer = new System.Threading.Timer((o) =>
           {
               try
               {
                   thread.Abort(o);
               }
               catch
               {
                   // the thread is done before Abort statement called
               }
           },new object(),sleeptime,System.Threading.Timeout.Infinite);
        }
    }

上面的代码只是示例,您可以通过另一种方式来处理任务或线程池,以降低创建线程的成本。