gpt4 book ai didi

c# - DB ConnectionState = Open 但 context.SaveChanges 抛出 "connection broken"异常

转载 作者:行者123 更新时间:2023-11-30 12:40:50 26 4
gpt4 key购买 nike

在我的服务中,我有一个后台线程,它会尽最大努力保存特定实体类型的对象流。代码大致如下:

        while (AllowRun)
{
try
{
using (DbContext context = GetNewDbContext())
{
while (AllowRun && context.GetConnection().State == ConnectionState.Open)
{
TEntity entity = null;
try
{
while (pendingLogs.Count > 0)
{
lock (pendingLogs)
{
entity = null;
if (pendingLogs.Count > 0)
{
entity = pendingLogs[0];
pendingLogs.RemoveAt(0);
}
}

if (entity != null)
{
context.Entities.Add(entity);
}
}
context.SaveChanges();
}
catch (Exception e)
{
// (1)
// Log exception and continue execution
}
}
}
}
catch (Exception e)
{
// Log context initialization failure and continue execution
}
}

(这主要是实际代码,我省略了一些不相关的部分,这些部分试图将弹出的对象保存在内存中,直到我们能够在 (1) 捕获异常时再次将内容保存到 DB > 阻止)

因此,从本质上讲,这是一个无限循环,试图从某个列表中读取项目并将它们保存到 Db。如果我们检测到与数据库的连接由于某种原因失败,它只会尝试重新打开它并继续。问题是有时(到目前为止我还没有弄清楚如何重现它),上面的代码在调用 context.SaveChanges() 时开始产生以下异常(在 (1 ) block ):

System.Data.EntityException: An error occurred while starting a transaction on the provider connection. See the inner exception for details. ---> 
System.InvalidOperationException: The requested operation cannot be completed because the connection has been broken.

错误已记录,但当执行返回到 context.GetConnection().State == ConnectionState.Open 检查时,它的计算结果为 true。因此,当上下文报告其数据库连接已打开时,我们处于一种状态,但我们无法针对该上下文运行查询。重新启动服务可解决问题(以及在调试器中扰乱 AllowRun 变量以强制重新创建上下文)。所以问题是因为我不能信任上下文的连接状态,我如何验证我可以对数据库运行查询?

此外,是否有一种干净的方法来确定连接是否处于“健康”状态?我的意思是,EntityException 本身并不表示我应该重置连接,只有当它的 InnerException 是带有某些特定消息的 InvalidOperationException 时,是的,是时候重置它。但是,现在我猜还会有其他情况,ConnectionState 指示一切正常,但我无法查询 DB。我能否主动捕捉它们,而不是等到它开始咬我?

最佳答案

日志频率是多少?

如果此循环花费的时间超过连接超时时间,则在执行 savechanges 时关闭连接。

while (pendingLogs.Count > 0)
{
lock (pendingLogs)
{
entity = null;
if (pendingLogs.Count > 0)
{
entity = pendingLogs[0];
pendingLogs.RemoveAt(0);
}
}

if (entity != null)
{
context.Entities.Add(entity);
}
}
context.SaveChanges();

关于c# - DB ConnectionState = Open 但 context.SaveChanges 抛出 "connection broken"异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40519027/

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