Azure表存储的ExecuteAsync()无法插入所有记录

Sam*_*eer 1 c# azure azure-table-storage async-await

我试图将10000条记录插入Azure表存储。我正在使用ExecuteAsync()实现它,但是不知何故,大约插入了7500条记录,其余的记录丢失了。我故意不使用await关键字,因为我不想等待结果,只想将它们存储在表中。以下是我的代码段。

private static async void ConfigureAzureStorageTable()
    {
        CloudStorageAccount storageAccount =
            CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
        CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
        TableResult result = new TableResult();
        CloudTable table = tableClient.GetTableReference("test");
        table.CreateIfNotExists();

        for (int i = 0; i < 10000; i++)
        {
            var verifyVariableEntityObject = new VerifyVariableEntity()
            {
                ConsumerId = String.Format("{0}", i),
                Score = String.Format("{0}", i * 2 + 2),
                PartitionKey = String.Format("{0}", i),
                RowKey = String.Format("{0}", i * 2 + 2)
            };
            TableOperation insertOperation = TableOperation.Insert(verifyVariableEntityObject);
            try
            {
                table.ExecuteAsync(insertOperation);
            }
            catch (Exception e)
            {

                Console.WriteLine(e.Message);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

该方法的使用是否有误?

sel*_*ape 5

还是await table.ExecuteAsync()。这将意味着此时ConfigureAzureStorageTable()将控制权返回给调用者,可以继续执行。

您在问题中遇到的问题的ConfigureAzureStorageTable()方式将继续进行到调用table.ExecuteAsync()并退出的位置,并且类似任务table将超出范围,而table.ExecuteAsync()任务仍未完成。

有关async void在SO和其他地方使用的许多警告,您也需要考虑。你可以很轻松拥有您的方法,async Task但在调用者不等待它尚未,但要返回的Task周围清洁终止等

编辑:一项附加功能-您几乎肯定要ConfigureAwait(false)await那儿使用,因为您似乎不需要保留任何上下文。这篇博客文章对此有一些指导,并且总体上讲是异步的。