我从另一个SO question找到了这个方法(功能?),我不确定如何使用它。我想用它来解决我的数据库(通过无线网络)的连接问题,然后重试或抛出其他异常。我的应用程序只有几个数据库访问功能,所以我只是要复制和粘贴所有内容,但如果我需要更改内容,我不想让每个函数更新10次。
我想要使用的方法:
private void Retry<T>(Action<T> retryAction) where T : DataContext, new()
{
var retryCount = 0;
using (var ctx = new T())
{
for (; ; )
{
try
{
retryAction(ctx);
break;
}
catch (SqlException ex)
{
if (!Enum.IsDefined(typeof(RetryableSqlErrors), ex.Number))
throw;
retryCount++;
if (retryCount > MAX_RETRY) throw;
Thread.Sleep(ex.Number == (int)RetryableSqlErrors.Timeout ?
longWait : shortWait);
}
}
}
}
我想传递给它的函数示例:
public async Task<List<EmployeeDisplay>> GetInspectorsAsync()
{
using (M1Context m1 = new M1Context())
{
var q = (from a in m1.Employees
where (a.lmeTerminationDate == null)
&& (a.lmeInspectorEmployee == -1)
orderby a.lmeEmployeeName
select new EmployeeDisplay
{
EmployeeID = a.lmeEmployeeID,
EmployeeName = a.lmeEmployeeName.ToUpper().Trim()
});
return await q.ToListAsync();
}
}
public async Task<List<Reason>> GetScrapReasonsAsync()
{
using (M1Context m1 = new M1Context())
{
Debug.WriteLine("getting scrap reasons");
var q = (from a in m1.Reasons
where a.xarReasonType.Trim().Equals("S")
select a);
return await q.ToListAsync();
}
}