مروری بر کاربردهای Action و Func - قسمت سوم
نویسنده: وحید نصیری
تاریخ: ۱۳۹۱/۰۵/۲۹ ۲۰:۱۹
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
try {
// code
} catch(Exception ex) {
// do something
}
void Execute(Action action) {
try {
action();
} catch(Exception ex) {
// log errors
}
}
Execute(() => {open a file});
public static class SafeExecutor
{
public static T Execute<T>(Func<T> operation)
{
try
{
return operation();
}
catch (Exception ex)
{
// Log Exception
}
return default(T);
}
}
var data = SafeExecutor.Execute<string>(() =>
{
// do something
return "result";
});
public static class RetryHelper
{
public static void RetryOperation(Action action, int numRetries, int retryTimeout)
{
if( action == null )
throw new ArgumentNullException("action");
do
{
try { action(); return; }
catch
{
if( numRetries <= 0 ) throw;
else
Thread.Sleep( retryTimeout );
}
} while( numRetries-- > 0 );
}
}
RetryHelper.RetryOperation(() => SomeFunction(), 3, 1000);
return default (T);