我要解决一个问题。 我想写数据库,但是我想知道如果失败,我该如何重试写数据库。就像我希望任务在写入数据库失败时重试。
我如何才能使逻辑写入数据库的SQL每5分钟重试一次,例如10次重试?
public async Task<string> Handler()
{
DoStuff1,2,3();
}
public async Task<string> Dostuff1,2,3()
{
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = connection;
cmd.CommandText = "InsertData";
cmd.Parameters.Add(new SqlParameter("Data", "TestData"));
cmd.ExecuteNonQuery();
return true;
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error");
}
}
我的新尝试:以下哪一项是正确的?
public async Task<string> Handler()
{
DatabaseSQLLogic1,2,3();
}
public async Task<string> DatabaseSQLLogic1,2,3()
{
var success = false;
var count = 0;
while(!success && count < 10)
{
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = connection;
cmd.CommandText = "InsertData";
cmd.Parameters.Add(new SqlParameter("Data", "TestData"));
cmd.ExecuteNonQuery();
return true;
}
}
}
success = true;
}
catch(Exception ex)
{
Console.WriteLine($"An error occurred doing the thing: {ex}");
count += 1;
}
}
// if success is still false, that means we our loop above failed after 10 attempts
if(success == false)
{
Console.WriteLine("Failed to do the thing after 10 attempts");
}
}
或
public async Task<string> Handler()
{
var success = false;
var count = 0;
while(!success && count < 10)
{
try
{
DatabaseSQLLogic1,2,3();
}
catch(Exception ex)
{
Console.WriteLine($"An error occurred doing the thing: {ex}");
count += 1;
}
}
// if success is still false, that means we our loop above failed after 10 attempts
if(success == false)
{
Console.WriteLine("Failed to do the thing after 10 attempts");
}
}
public async Task<string> DatabaseSQLLogic1,2,3()
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = connection;
cmd.CommandText = "InsertData";
cmd.Parameters.Add(new SqlParameter("Data", "TestData"));
cmd.ExecuteNonQuery();
return true;
}
}
}
答案 0 :(得分:1)
将“数据库”排除在这个问题之外,因为可以用任何逻辑替换它。
var success = false;
var count = 0;
while(!success && count < 10)
{
try
{
DoThing(); // database call, webservice call, etc
success = true;
}
catch(Exception ex)
{
Console.WriteLine($"An error occurred doing the thing: {ex}");
count += 1;
}
}
// if success is still false, that means we our loop above failed after 10 attempts
if(success == false)
{
Console.WriteLine("Failed to do the thing after 10 attempts");
}
当然,用实际的日志语句替换Console.WriteLine
。
答案 1 :(得分:0)
一个气质的旧系统需要重试逻辑才能读取平面文件中的数据。
根据这些经验,下面是一些建议。