【问题标题】:How to create new Async Task can keep CurrentUnitOfWork in aspboilerplate如何创建新的异步任务可以将 CurrentUnitOfWork 保留在 aspboilerplate 中
【发布时间】:2019-03-10 03:59:49
【问题描述】:

我有这样的带有 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

        }

    }
});

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

【问题讨论】:

  • 我不知道这是否是根本原因,但你不应该使用StartNew。如果您删除 StartNew 包装器并直接运行 async 代码会发生什么?

标签: c# boilerplate


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-04
    相关资源
    最近更新 更多