DbExecutionStrategy重试超过MaxRetryCount

时间:2016-03-20 01:54:34

标签: c# mysql entity-framework entity-framework-6

我使用DbExecutionStrategy在查询服务器时使我的程序支持连接超时,但它没有按预期工作。

这是我的班级:

public class MyExecutionStrategy : DbExecutionStrategy
{
    static MyExecutionStrategy()
    {
        RetriesPerInstance = new Dictionary<int, int>();
    }

    private const int MaxRetryCount = 5;
    private static TimeSpan _maxDelay = new TimeSpan(0, 0, 3);



    private int _instanceNo;

    public MyExecutionStrategy() : base(MaxRetryCount, _maxDelay)
    {
        _instanceNo = ++TotalInstances;
        RetriesPerInstance[_instanceNo] = 0;
    }

    public static Dictionary<int, int> RetriesPerInstance { get; private set; }

    public static int TotalRetries
    {
        get
        {
            return RetriesPerInstance.Values.Sum();
        }
    }

    public static int TotalInstances { get; private set; }

    protected override bool ShouldRetryOn(Exception ex)
    {
        RetriesPerInstance[_instanceNo]++;

        return true;
    }
} 

这是我的问题:

private void Form1_Load(object sender, EventArgs xe)
    {
        var dengineEntities = new dengineEntities();

        try
        {
            var proj = dengineEntities.motorista_erro.ToArray();
        }
        catch (Exception e)
        {
            var tries = MyExecutionStrategy.TotalRetries;
        }
    }

对于单个ToArray,它返回42 Retries,并在抛出RetryLimitExceededException之前实例化14个策略。

为什么它不停止5次尝试以及为什么它为单个查询创建多个实例?有什么东西我没看到?

enter image description here

这些是我的上下文类:

public partial class dengineEntities : DbContext
{
    public dengineEntities()
        : base("name=dengineEntities")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public virtual DbSet<motorista_erro> motorista_erro { get; set; }

}
public partial class motorista_erro
{
    public int MOT_ID { get; set; }
    public string MOT_NOME { get; set; }
    public bool MOT_SIT_FUNC_ID { get; set; }
    public int IDEMP { get; set; }
}
<connectionStrings>
 <add name="dengineEntities" ...etc...etc../>
</connectionStrings>

1 个答案:

答案 0 :(得分:0)

它在5次重试时停止,查看RetriesPerInstance屏幕截图中的值,每个值有6或0. 6次重试意味着重试5次,第6次停止。

所以听起来你的问题就在其他地方。 Form1_Load被调用了多少次?