在执行 Azure Table 存储的插入操作后,我应该从 C# 中的 Async 方法 return 做什么?

What should I return from my Async method in C# after doing the insert operation of Azure Table Storage?

我有一个名为 LogCloudModel 的异步方法。我对方法的 return 类型感到困惑。它调用了一个异步方法 InsertIntoTableStorage。下面是完整的代码示例。

     private static async void LogCloudModel(ModelExecutionContext context)
     {
        var azureStorageAccount = new AzureStorageAccount();
        var cloudModelDetail = new CloudModelDetail();

        //Populate the cloud model
        var cloudModelDetailCollection = PopulateCloudModel(context, cloudModelDetail);

        if (cloudModelDetailCollection == null) return;
        await InsertIntoTableStorage(azureStorageAccount, cloudModelDetailCollection);
        LogTableStorageTransactionResult(azureStorageAccount, operationResult, cloudModelDetail.PartitionKey, cloudModelDetail.RowKey);
      }

目前,我return什么都没有(void)。我的实现是否正确?

你 return 由你决定。在这种情况下,你应该至少 return Task 而不是 void,但如果你需要 return 多于(无)你可以 return a Task<T>.

除非你写的是 event handler return Task 而不是 void,这样调用者就可以 await:

private static async Task LogCloudModel(ModelExecutionContext context)
     {
        var azureStorageAccount = new AzureStorageAccount();
        var cloudModelDetail = new CloudModelDetail();

        //Populate the cloud model
        var cloudModelDetailCollection = PopulateCloudModel(context, cloudModelDetail);

        if (cloudModelDetailCollection == null) return;
        await InsertIntoTableStorage(azureStorageAccount, cloudModelDetailCollection);
        LogTableStorageTransactionResult(azureStorageAccount, operationResult, cloudModelDetail.PartitionKey, cloudModelDetail.RowKey);
      }

异步函数仅限于以下return类型:

  • void
  • Task
  • Task<TResult>

returning Task 而不是 void 的主要好处是它允许调用者将自己的延续附加到 returned 任务,这允许检测任务何时失败。

除非您从事件处理程序调用异步方法,否则我不会returnvoid