如何创建新的异步任务可以将CurrentUnitOfWork保留在aspboilerplate中

时间:2019-03-10 03:59:49

标签: c# boilerplate

我有带有unitofwork标签的API,像这样

[HttpPost]
[Route("Book/ReadBookRequest")]
[UnitOfWork(scope: TransactionScopeOption.RequiresNew, isTransactional: true)]

然后我像这样在api中启动新任务:

var taskBusiness = Task.Factory.StartNew(async () =>
{
    using (_abpSession.Use(tenantInfo.Id, _abpSession.UserId))
    {
         using (var uow = _unitOfWorkManager.Begin(new UnitOfWorkOptions { IsTransactional = false, Scope = System.Transactions.TransactionScopeOption.Required }))
        {
            CurrentUnitOfWork(1) //Current unit of work of uow
            await InsertDatabase();
            using (var uow2 = _unitOfWorkManager.Begin(new UnitOfWorkOptions { IsTransactional = false, Scope = System.Transactions.TransactionScopeOption.Required }))
            {
                //Save data to dabase
                CurrentUnitOfWork(2) //Current unit of work of uow2
                uow2.Complete()
            }
            CurrentUnitOfWork(1) //Now current unit of work of uow = null

        }

    }
});

请帮助我知道为什么在启动新的uow后我的 CurrentUnitOfWork(1)为空。以及如何在我的情况下解决此问题。 我的流程: 调用api->创建响应,任务仍在运行以将数据保存到数据库 谢谢!

1 个答案:

答案 0 :(得分:0)

用Task.Run(()=>块代码)替换StartNew,它对我有用。谢谢Stephen Cleary。