我有一个名为TableStorageController.cs
public class TableStorageController
{
private static Dictionary<string, BlockingCollection<CloudModelDetail>> s_dictionary = new Dictionary<string, BlockingCollection<CloudModelDetail>>();
private static StorageAccount s_azureStorageAccount;
private readonly CloudModelDetail _cloudModelDetail;
private static CancellationTokenSource s_cancellationTokenSource = new CancellationTokenSource();
private static int s_retailerId;
/// <summary>
/// Static task to log transactions to Azure Table Storage after every 5 minutes.
/// </summary>
static TableStorageController()
{
try
{
Task.Run(async () =>
{
while (true)
{
await Task.Delay(300000, s_cancellationTokenSource.Token);
foreach (var retaileridkey in s_dictionary.Keys)
{
var batchOperation = new TableBatchOperation();
while (s_dictionary[retaileridkey].Count != 0 && batchOperation.Count < 101)
{
batchOperation.InsertOrMerge(s_dictionary[retaileridkey].Take());
}
if (batchOperation?.Count != 0)
await s_azureStorageAccount.VerifyCloudTable.ExecuteBatchAsync(batchOperation);
}
}
});
}
catch (Exception ex)
{
s_log.Fatal("Azure task run failed", ex);
}
}
}
此任务旨在每5分钟运行一次,并将字典中存在的任何项目记录到Azure表存储。 在本地运行我的代码时,我可以看到它在每5分钟后被触发。 但是,不管怎样,一旦在另一个环境(生产)中部署之后,它就会失败。
有谁可以指出我错过了什么?
注意:我从未遇到异常Azure task run failed
。
答案 0 :(得分:0)
尝试将异常处理放在 Task.Run
块中。您没有等待对Task.Run的调用,因此异常将被忽视。由于await Task.Delay
已经是非阻塞的,我不明白为什么你需要额外的任务。试试这个:
static async void TableStorageController()
{
try
{
while (true)
{
await Task.Delay(TimeSpan.FromMinutes(5), s_cancellationTokenSource.Token);
foreach (var retaileridkey in s_dictionary.Keys)
{
var batchOperation = new TableBatchOperation();
while (s_dictionary[retaileridkey].Count != 0 && batchOperation.Count < 101)
{
batchOperation.InsertOrMerge(s_dictionary[retaileridkey].Take());
}
if (batchOperation?.Count != 0)
await s_azureStorageAccount.VerifyCloudTable.ExecuteBatchAsync(batchOperation);
}
}
}
catch (Exception ex)
{
s_log.Fatal("Azure task run failed", ex);
}
}
顺便说一句,您也可以使用计时器而不是Task.Delay
和CancellationToken