C#: Executing action multiple times with exception handling

There are times when you want to execute a function multiple times while watching out for any exceptions.
 public void ExecuteAction(Action action, int numberOfTries = 2)  
     {  
       if (numberOfTries <= 0)  
         return;  
       try  
       {  
         action();  
       }  
       catch  
       {  
         ExecuteAction(action, --numberOfTries);  
       }  
     }  


You can use the function like this
 ExecuteAction(() => Clipboard.SetText("Your Text"), 2);  


One of those scenarios is when you are trying to store some text on clipboard like this:
 try  
       {  
         Clipboard.SetText("Your Text");  
       }  
       catch (System.Runtime.InteropServices.COMException)  
       {  
         try  
         {  
           Clipboard.SetText("Your Text");  
         }  
         catch (System.Runtime.InteropServices.COMException)  
         {  
         }  
       }  

Comments

Popular posts from this blog

WPF How to Dispose ViewModel when the associated UserControl (Not Window) closes?

C# How to unit test Dispatcher

WPF: How to Deep Copy WPF object (e.g. UIElement) ?