HostingEnvironment.QueueBackgroundWorkItem中的事务范围超时

时间:2019-08-07 14:03:08

标签: c# ef-core-2.2

我们正在使用HostingEnvironment.QueueBackgroundWorkItem对长时间运行的后台任务进行排队。这很好用,但是,当事务超时时,我们没有任何异常,线程似乎被杀死或挂起。

有人知道这里发生了什么吗?我期待交易超时异常或其他相关问题... 我们注意到,使用DbContext时,线程在超时后挂起,如果没有DbContext,我们将导致事务超时。

问题:为什么在使用EF DbContext时我们没有使事务超时异常?

Hanging thread screenshot

    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Threading;
    using System.Web;
    using System.Web.Hosting;
    using System.Web.Mvc;
    using Timer = System.Timers.Timer;

    namespace WebApplication5.Controllers
    {
        public class HomeController: Controller
        {
            public ActionResult Index()
            {
        ViewBag.Title = "Home Page";

        HostingEnvironment.QueueBackgroundWorkItem(cancellationToken =>
        {
            try
            {
                try
                {
                    var dbContext = new TestDbContext();
                    using (var backgroundTimer = CreateTimerWhichExtendsLocks((10)))
                    {
                        using (var Tran =
                            TransactionScopeBuilder.CreateWithDefaultIsolationLevel(timeout: new TimeSpan(0, 0, 30)))
                        {
                            try
                            {
                                int i = 0;
                                do
                                {
                                    var d = dbContext.MyTestEntities.SingleOrDefault(x => x.Id == 1);
                                    Thread.Sleep(500);
                                    i++;
                                    Debug.WriteLine(i);
                                } while (i < 100);
                            }
                            catch (Exception e)
                            {
                                Debug.WriteLine(e);
                                throw;
                            }

                            tran.Complete();
                        }
                    }
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e);
                    throw;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                throw;
            }
        });

        return View();
    }

    private static Timer CreateTimerWhichExtendsLocks(int lockDurationInMs)
    {
        var backgroundTimer = new Timer(300);
        backgroundTimer.Elapsed += (sender, e) =>
        {
            Debug.WriteLine(DateTime.Now);
        };
        backgroundTimer.Start();
        return backgroundTimer;
    }
}

}

1 个答案:

答案 0 :(得分:1)

这似乎是efcore 2.x中的一个已知问题,该问题已在3.x版本中修复。

https://github.com/aspnet/EntityFrameworkCore/issues/14218

当事务中的操作花费的时间比环境事务的超时时间长时,连接将被环境事务关闭,但是内部方法不知道此情况,并尝试重新打开连接,这会使程序陷入困境陷入僵局。