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.
One of those scenarios is when you are trying to store some text on clipboard like this:
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
Post a Comment