[英]How can I use this method to reuse my try/catch?
我從另一個SO問題中找到了這種方法(功能?),我不確定如何使用它。 我想用它來捕獲到數據庫(通過無線網絡)的連接問題,然后重試或引發其他異常。 我的應用程序僅具有幾個數據庫訪問功能,因此我將只復制和粘貼所有內容,但是如果需要更改某些內容,我不想每次更新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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.