using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace AgileConfig.Server.Common
{
public class FunctionUtil
{
///
/// 尝试运行一个Func几次
///
///
///
///
///
public static T TRY(Func func, int tryCount)
{
if (func == null)
{
throw new ArgumentNullException("func");
}
T result = default(T);
for (int i = 0; i < tryCount; i++)
{
try
{
result = func();
break;
}
catch
{
if (i == (tryCount - 1))
{
throw;
}
}
}
return result;
}
///
/// 尝试执行一个异步方法多次
///
///
///
///
///
public static async Task TRYAsync(Func> func, int tryCount)
{
if (func == null)
{
throw new ArgumentNullException("func");
}
T result = default(T);
for (int i = 0; i < tryCount; i++)
{
try
{
result = await func();
break;
}
catch
{
if (i == (tryCount - 1))
{
throw;
}
}
}
return result;
}
///
/// 尝试执行一个异步方法多次 , 直接吞掉异常
///
///
///
///
///
public static async Task EATAsync(Func> func, int tryCount)
{
if (func == null)
{
throw new ArgumentNullException("func");
}
T result = default(T);
for (int i = 0; i < tryCount; i++)
{
try
{
result = await func();
break;
}
catch
{
}
}
return result;
}
///
/// 尝试运行一个Action几次
///
///
///
///
///
public static void TRY(Action act, int tryCount)
{
if (act == null)
{
throw new ArgumentNullException("act");
}
for (int i = 0; i < tryCount; i++)
{
try
{
act();
break;
}
catch
{
if (i == (tryCount - 1))
{
throw;
}
}
}
}
}
}