M
M
martensit2018-04-16 10:33:17
C++ / C#
martensit, 2018-04-16 10:33:17

Is there a simpler “repeat until success” snippet?

while (true)
   {
      try
      {
         File.WriteAllText(@"C:\\serv1.txt", "text");
         break;
      }
      catch (Exception)
      {
         Thread.Sleep(300);
      }
   }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Pavlov, 2018-04-16
@martensit

Try this method (no way to test). The input is a delegate that needs to be executed.

void UntilSuccess(Action action) {
  if (action == null)
    throw new ArgumentNullException();

  while (true) {
      try
      {
         action.Invoke();
         break;
      }
      catch { Thread.Sleep(300); }
  }
}

// Использовать так:
UntilSuccess(() => File.WriteAllText(@"C:\\serv1.txt", "text"));

D
Dmitry Eremin, 2018-04-16
@EreminD

and if in a recursion?
type

private void writeText(){
  try
      {
         File.WriteAllText(@"C:\\serv1.txt", "text");
      }
      catch (Exception)
      {
         Thread.Sleep(300);
         writeText();
      }
}

And just call writeText();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question