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

how to time limit C# foreach loop to execute an iteration with max time limit

如何限制 C# foreach 循环的时间,每次迭代都应该 运行 正常,当上一次迭代花费的时间超过 30 秒时转到下一次迭代。

使用过秒表、计时器...但这些允许每 30 秒 运行 迭代一次,有人能帮忙吗...

您必须为每次迭代生成一个单独的线程。但是多亏了匿名委托,你几乎可以让它看起来像是在本地执行的代码。

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.
   }

只需使用一些线程:

   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);
        }
    }

上面的代码只是示例,您可以通过其他方式(例如任务或线程池)来降低创建线程的成本。

或者这里有一个 Tasks 示例。

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

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