D
D
delitme2015-02-14 14:40:16
Programming
delitme, 2015-02-14 14:40:16

How to repeat current iteration while C#?

Hello.
Can you please tell me how to repeat the current iteration while C# ?
Those. example

while (условие) {
    код код код код
    код код код код
    
    if (условие) {
        "перезапусить" текущую итерацию заново
    }

    код код код код
    код код код код
}

It is necessary that, if the if condition is met, start ( restart ) the current iteration on a new one. Unfortunately, I couldn't find the answer on google. Only continue is suggested. But it skips the current iteration and starts the next one, and I need to "restart" the current one . Is it possible to?
See the situation. Iterates through the list of files to upload using while. Suddenly it happens that the server responded to some file, for example, with a 503 error. You need to download this file over a new one at the same moment. And if continue, then this file will be skipped and we will move on to the next file in the list. Or am I wrong?

Answer the question

In order to leave comments, you need to log in

5 answer(s)
A
Alexey Nemiro, 2015-02-14
@delitme

Depends on logic. If, as shown below, then continue can be used :

int i = 0;
bool b = false;
while (i < 10)
{
  Console.WriteLine("Текущее: {0}", i);
      
  if (i == 5 && !b)
  {
    b = true;
    continue;
  }
      
  i++;
}

As a last resort, there is goto :
int i = 0; 
bool b = false;
while (i < 10)
{
  again: // точка возврата
  Console.WriteLine("Текущее: {0}", i);
      
  if (i == 5 && !b)
  {
    b = true;
    goto again;
  }
      
  i++;
}

View online example
However, such transitions should not be abused. From the abundance of goto statements in the code, the programmer may have a brain break, which will lead to the inevitable death of the project and its revival in a new form, unless, of course, the programmer himself hoards. That injury is serious :-) If there is an opportunity, desire and time, it is better to change the logic so that you do not have to make such “jumps”.
To get files or work with files in general (waiting for read or delete access, getting data from the network, etc.), you can use a nested loop that will try to complete the task until it is successfully completed or the allotted time has not expired. time to complete the task (or number of attempts):
// пауза между попытками (100 мс)
var interval = new TimeSpan(0, 0, 0, 0, 100); 
// максимальное время ожидания (1 секунда)
var timeout  = new TimeSpan(0, 0, 0, 1); 
while (true)
{
  var totalTime = new TimeSpan(); // счетчик времени
  var заданиеВыполнено = false;

  while(!заданиеВыполнено) // повторять, пока задание не будет выполнено
  {
    try
    {
      // тут код задания
      // если ошибок не будет, то
      заданиеВыполнено = true; // работа цикла будет завершена
    }
    catch
    {
      // если ошибка, делаем паузу
      System.Threading.Thread.Sleep(100);
      // увеличиваем счетчик времени
      totalTime += interval;
      if (totalTime > timeout)
      {
        // превышен таймаут, выходим
        Console.WriteLine("Превышено время ожидания");
        break;
      }
    }
  }
}

S
Sergey Mozhaykin, 2015-02-14
@smozhaykin

Use, for example, a queue. Add all the files to be processed to it. In the loop until the queue is empty, take the first element and do the necessary actions with this file. If everything is successful, remove the element from the queue. If there is an error, just continue (without dequeuing) and the same file will be processed at the next iteration of the loop.

A
Armenian Radio, 2015-02-14
@gbg

Backfilling question - how does the "current" differ from the "next"? continue implements exactly what you need.

M
Mrrl, 2015-02-14
@Mrl

I would do like this:

while (условие) {
    do {
        код код код код
        код код код код
    }while (условие);

    код код код код
    код код код код
}

But this if "restart the current iteration" does not require additional code. If required, replace do...while with an infinite for(;;) loop with break shortly before the end.

V
Vladimir S, 2015-02-26
@hePPer

See the situation. Iterates through the list of files to upload using while. Suddenly it happens that the server responded to some file, for example, with a 503 error. You need to download this file over a new one at the same moment. And if continue, then this file will be skipped and we will move on to the next file in the list. Or am I wrong?

both right and wrong. in your case, it is enough to start either a counter variable or a list of files to be uploaded before starting the cycle. at the beginning of the loop, load the file and if it is loaded, set the flag = loaded, in the middle check this flag - if not loaded, then continue, otherwise continue the loop after the condition, where to reset the load flag, change the counter and manipulate the file. - and no crutches.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question