首页 > 解决方案 > 执行后能够恢复(将文件更新到 Blob 存储)和(通过 EF Core 添加/更新数据库)

问题描述

我的计划是同时发生 2 个动作。如果 1 失败则恢复,但我很难找到它的方法。

伪代码是

public async Task<ActionResult> Upload(<parameter-lists>)
{
  // authentication
  // verify file (name, size, ...)

  // PORTION THAT I HAVE DIFFICULTY
  // trying to do [database save] and [upload to storage blob] at the same time
  // if success, then good. return response
  // if [at least 1] fail, then REVERT both processes ([database save] and [upload to storage blob])
}

我愿意接受任何建议。

============

编辑1,有朋友有这个建议。

try 
{
  await Task.WhenAll(
    UpdateDatabaseAsync(),
    UpdateBlobStorageAsync(),
  );
} 
catch (DbUpdateException)
{
  await RollbackBlobStorageAsync();
}
catch (BlobStorageUpdateException)
{
  await RollbackDatabaseAsync();
}

============

我愿意接受任何建议。

标签: c#asp.net-coreconcurrencytransactionsazure-blob-storage

解决方案


实际上你可以使用事务。最好阅读文档文档

谈到您的建议,请记住数据库上下文不是线程安全的。

var tasks = Task.WhenAll(
    UpdateDatabaseAsync(),
    UpdateBlobStorageAsync(),
  );

try{
    await tasks;
}
catch(exception ex){
    foreach (var inx in tasks.Exception.InnerExceptions)
    {
        log(inx);
    }
}

if(tasks.IsFaulted){
   await RollbackBlobStorageAsync();
   await RollbackDatabaseAsync();
}

推荐阅读