gpt4 book ai didi

entity-framework-4 - EF 4.0 : Save Changes Retry Logic

转载 作者:行者123 更新时间:2023-12-04 07:59:46 24 4
gpt4 key购买 nike

我想为所有实体 SaveChanges 方法调用实现一个应用程序范围的重试系统。

技术:
Entity Framework 4.0
.Net 4.0

namespace Sample.Data.Store.Entities {  
public partial class StoreDB
{
public override int SaveChanges(System.Data.Objects.SaveOptions options)
{
for (Int32 attempt = 1; ; )
{

try
{
return base.SaveChanges(options);
}
catch (SqlException sqlException)
{
// Increment Trys
attempt++;

// Find Maximum Trys
Int32 maxRetryCount = 5;

// Throw Error if we have reach the maximum number of retries
if (attempt == maxRetryCount)
throw;

// Determine if we should retry or abort.
if (!RetryLitmus(sqlException))
throw;
else
Thread.Sleep(ConnectionRetryWaitSeconds(attempt));
}
}
}

static Int32 ConnectionRetryWaitSeconds(Int32 attempt)
{
Int32 connectionRetryWaitSeconds = 2000;

// Backoff Throttling
connectionRetryWaitSeconds = connectionRetryWaitSeconds *
(Int32)Math.Pow(2, attempt);

return (connectionRetryWaitSeconds);
}



/// <summary>
/// Determine from the exception if the execution
/// of the connection should Be attempted again
/// </summary>
/// <param name="exception">Generic Exception</param>
/// <returns>True if a a retry is needed, false if not</returns>
static Boolean RetryLitmus(SqlException sqlException)
{
switch (sqlException.Number)
{
// The service has encountered an error
// processing your request. Please try again.
// Error code %d.
case 40197:
// The service is currently busy. Retry
// the request after 10 seconds. Code: %d.
case 40501:
//A transport-level error has occurred when
// receiving results from the server. (provider:
// TCP Provider, error: 0 - An established connection
// was aborted by the software in your host machine.)
case 10053:
return (true);
}

return (false);
}
}
}

问题:

发生错误后如何运行 StoreDB.SaveChanges 以在新的数据库上下文上重试?类似于分离/附加的东西可能会派上用场。

提前致谢!巴特

最佳答案

查看 SQL Azure 的 transient 故障处理框架,here .它非常通用,并且很容易修改以包含后端的重试逻辑。

关于entity-framework-4 - EF 4.0 : Save Changes Retry Logic,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3023771/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com