草庐IT

c# - 回滚事务时出现异常 - 连接已关闭?

coder 2024-06-03 原文

使用 Entity Framework 6.0.0,我在关闭事务时看到异常。

我们一直在对表进行并发更改时遇到问题,所以我将其包装在一个事务中,现在我在回滚时遇到异常。

代码:

public LockInfo getSharedLock(string jobid)
{
    using (var myDbContext = new MyDbContext())
    {
        using (var transaction = myDbContext.Database.BeginTransaction())
        {
            try
            {
                this.logger.log("Attempting to get shared lock for {0}", jobid);

                var mylocks =
                    myDbContext.joblocks.Where(j => j.customerid == this.userContext.customerid)
                        .Where(j => j.jobid == jobid)
                        .Where(j => j.operatorid == this.userContext.operatorid);

                var exclusiveLock = mylocks.FirstOrDefault(
                    j => j.lockstatus == LockInfo.LockState.Exclusive);
                if (exclusiveLock != null)
                {
                    this.logger.log("{0} already had exclusive lock, ignoring", jobid);
                    return LockInfo.populate(exclusiveLock);
                }

                var sharedLock = mylocks.FirstOrDefault(
                    j => j.lockstatus == LockInfo.LockState.Shared);
                if (sharedLock != null)
                {
                    this.logger.log("{0} already had shared lock, ignoring", jobid));
                    sharedLock.lockdt = DateTime.Now;
                    myDbContext.SaveChanges();

                    return LockInfo.populate(sharedLock);
                }

                var joblock = new joblock
                {
                    customerid = this.userContext.customerid,
                    operatorid = this.userContext.operatorid,
                    jobid = jobid,
                    lockstatus = LockInfo.LockState.Shared,
                    sharedLock.lockdt = DateTime.Now
                };

                myDbContext.joblocks.Add(joblock);
                myDbContext.SaveChanges();
                transaction.Commit();

                this.logger.log("Obtained shared lock for {0}", jobid);
                return LockInfo.populate(joblock);
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                this.logger.logException(ex, "Exception in getSharedLock(\"{0}\")", jobid);
                throw;
            }
        }
    }
}

您可以在上面的代码中看到日志记录。我们也在数据库中启用了日志记录。日志跟踪:

===================
NORMAL    TicketLockController.getLock("AK2015818002WL")
===================
SQL    Opened connection at 9/22/2015 2:47:49 PM -05:00
===================
SQL    Started transaction at 9/22/2015 2:47:49 PM -05:00
===================
NORMAL    Attempting to get shared lock for AK2015818002WL
===================
SQL    SELECT TOP (1) [Extent1].[customerid] AS [customerid]
    ,[Extent1].[jobid] AS [jobid]
    ,[Extent1].[lockdtdate] AS [lockdtdate]
    ,[Extent1].[lockdttime] AS [lockdttime]
    ,[Extent1].[operatorid] AS [operatorid]
    ,[Extent1].[lockstatus] AS [lockstatus]
    ,[Extent1].[changes] AS [changes]
FROM [dbo].[joblock] AS [Extent1]
WHERE ([Extent1].[customerid] = 'TESTTK')
    AND ([Extent1].[jobid] = 'AK2015818002WL')
    AND ([Extent1].[operatorid] = 'ADMIN')
    AND (N'Exclusive' = [Extent1].[lockstatus])
===================
SQL    SELECT TOP (1) [Extent1].[customerid] AS [customerid]
    ,[Extent1].[jobid] AS [jobid]
    ,[Extent1].[lockdtdate] AS [lockdtdate]
    ,[Extent1].[lockdttime] AS [lockdttime]
    ,[Extent1].[operatorid] AS [operatorid]
    ,[Extent1].[lockstatus] AS [lockstatus]
    ,[Extent1].[changes] AS [changes]
FROM [dbo].[joblock] AS [Extent1]
WHERE ([Extent1].[customerid] = 'TESTTK')
    AND ([Extent1].[jobid] = 'AK2015818002WL')
    AND ([Extent1].[operatorid] = 'ADMIN')
    AND (N'Shared' = [Extent1].[lockstatus])
===================
SQL    INSERT [dbo].[joblock] (
    [customerid]
    ,[jobid]
    ,[lockdtdate]
    ,[lockdttime]
    ,[operatorid]
    ,[lockstatus]
    ,[changes]
    )
VALUES (
    @0
    ,@1
    ,@2
    ,@3
    ,@4
    ,@5
    ,NULL
    )
===================
SQL    Closed connection at 9/22/2015 2:47:50 PM -05:00
===================
EXCEPTION    Unhandled exception caught: The underlying provider failed on Rollback.
===================
EXCEPTION    Inner Exception: Value cannot be null.
Parameter name: connection

两次选择都成功了,然后由于某种原因插入失败了。抛出异常,并且由于某种原因连接在 Rollback() 执行之前关闭。

知道我做错了什么吗?

==== 添加堆栈跟踪 ====

外部异常的堆栈跟踪:

   at System.Data.Entity.Core.EntityClient.EntityTransaction.Rollback()
   at korterra.kt_api.Shared.TicketLockWrangler.getSharedLock(String jobid)
   at korterra.kt_ws.ApiControllers.Shared.TicketLockController.getSharedLock(TicketLockDTO ticketLockDTO)
   at lambda_method(Closure , Object , Object[] )
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__18`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__18`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Filters.AuthorizationFilterAttribute.<ExecuteAuthorizationFilterAsyncCore>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext()

内部异常的堆栈跟踪:

   at System.Data.Entity.Utilities.Check.NotNull[T](T value, String parameterName)
   at System.Data.Entity.Infrastructure.Interception.DbTransactionInterceptionContext.WithConnection(DbConnection connection)
   at System.Data.Entity.Infrastructure.Interception.DbTransactionDispatcher.Rollback(DbTransaction transaction, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Core.EntityClient.EntityTransaction.Rollback()

最佳答案

在讨论之后,我开始在尝试回滚之前记录异常 - 这揭示了错误。

交易陷入僵局:

Exception in getSharedLock("ticketnumber123456"): An error occurred while updating the entries. See the inner exception for details.

Inner Exception: An error occurred while updating the entries. See the inner exception for details.

Inner Exception: Transaction (Process ID 139) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

根据我的阅读,当您被告知某个事务已成为死锁受害者时,它已经被回滚。也许这就是我们得到异常的原因?

解决方法似乎是要么识别我们何时陷入僵局而不回滚,要么不使用事务,并在我们遇到主键冲突时重试。

关于c# - 回滚事务时出现异常 - 连接已关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32728267/

有关c# - 回滚事务时出现异常 - 连接已关闭?的更多相关文章

  1. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

  2. ruby - 在 64 位 Snow Leopard 上使用 rvm、postgres 9.0、ruby 1.9.2-p136 安装 pg gem 时出现问题 - 2

    我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po

  3. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  4. ruby - 我可以使用 aws-sdk-ruby 在 AWS S3 上使用事务性文件删除/上传吗? - 2

    我发现ActiveRecord::Base.transaction在复杂方法中非常有效。我想知道是否可以在如下事务中从AWSS3上传/删除文件:S3Object.transactiondo#writeintofiles#raiseanexceptionend引发异常后,每个操作都应在S3上回滚。S3Object这可能吗?? 最佳答案 虽然S3API具有批量删除功能,但它不支持事务,因为每个删除操作都可以独立于其他操作成功/失败。该API不提供任何批量上传功能(通过PUT或POST),因此每个上传操作都是通过一个独立的API调用完成的

  5. ruby-on-rails - Rails - 乐观锁定总是触发 StaleObjectError 异常 - 2

    我正在学习Rails,并阅读了关于乐观锁的内容。我已将类型为integer的lock_version列添加到我的articles表中。但现在每当我第一次尝试更新记录时,我都会收到StaleObjectError异常。这是我的迁移:classAddLockVersionToArticle当我尝试通过Rails控制台更新文章时:article=Article.first=>#我这样做:article.title="newtitle"article.save我明白了:(0.3ms)begintransaction(0.3ms)UPDATE"articles"SET"title"='dwdwd

  6. ruby - 无法在 60 秒内获得稳定的 Firefox 连接 (127.0.0.1 :7055) - 2

    我使用的是Firefox版本36.0.1和Selenium-Webdrivergem版本2.45.0。我能够创建Firefox实例,但无法使用脚本继续进行进一步的操作无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055)错误。有人能帮帮我吗? 最佳答案 我遇到了同样的问题。降级到firefoxv33后一切正常。您可以找到旧版本here 关于ruby-无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055),我们在StackOverflow上找到一个类

  7. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  8. ruby - #之间? Cooper 的 *Beginning Ruby* 中的错误或异常 - 2

    在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee

  9. c# - 如何在 ruby​​ 中调用 C# dll? - 2

    如何在ruby​​中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL

  10. ruby - 在 Ruby 中重新分配常量时抛出异常? - 2

    我早就知道Ruby中的“常量”(即大写的变量名)不是真正常量。与其他编程语言一样,对对象的引用是唯一存储在变量/常量中的东西。(侧边栏:Ruby确实具有“卡住”引用对象不被修改的功能,据我所知,许多其他语言都没有提供这种功能。)所以这是我的问题:当您将一个值重新分配给常量时,您会收到如下警告:>>FOO='bar'=>"bar">>FOO='baz'(irb):2:warning:alreadyinitializedconstantFOO=>"baz"有没有办法强制Ruby抛出异常而不是打印警告?很难弄清楚为什么有时会发生重新分配。 最佳答案

随机推荐