【发布时间】:2019-08-12 14:38:03
【问题描述】:
我们正在使用 HostingEnvironment.QueueBackgroundWorkItem 对长时间运行的后台任务进行排队。这很好用,但是,当事务超时时,我们没有收到任何异常并且线程似乎被杀死或挂起。
有人知道这里发生了什么吗?我期待一个事务超时异常或相关的东西...... 我们注意到,当使用 DbContext 时,线程在超时后挂起,没有 DbContext,我们会遇到事务超时。
问题:为什么我们在使用 EF DbContext 时没有得到事务超时异常?
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;
}
}
}
【问题讨论】:
-
你能分享一些代码吗?您的尝试是在 QueueBackgroundWorkItem 方法内部还是外部? (它应该在 btw 里面)
-
我已经更新了帖子。
-
那么,您希望事务范围在时间用完时准确地抛出异常吗?不幸的是,只有在调用
transaction.Complete()之后才会抛出异常。看看这个帖子stackoverflow.com/questions/10055491/…
标签: c# ef-core-2.2