Performing conditional update and/or batch update with Windows Azure Table Storage
Here is a Windows Azure Table Update scenario which I found very useful to share:
You objective is to write some code to either do batch update and individual update in Windows Azure tables with or without ETag.
To handle both batch update and individual update process, you will be having two threads.
You created a list of entities and kept them in memory. And let’s assume that your don’t have ETag associated with it.
Thread 1: Batch Update Thread based on Timer:
foreach (Job job in jobsToUpdate)
{
job.JobInvalidAtUtc = DateTime.UtcNow + JobSystemConfiguration.InvalidAfterInSec;
tableContext.UpdateObject(job);
}
try
{
// ContinueOnError specifies that subsequent operations are attempted even if an
//error occurs in one of the operations.
DataServiceResponse response = tableContext.SaveChangesWithRetries(SaveChangesOptions.ContinueOnError);
}
catch (DataServiceRequestException ex)
{
// Pre-condition failed, meaning some other thread is modifying the same job
if (ex.Response.First().StatusCode != 412)
{
tracker.TraceEvent(JobDiag.ErrorTraceCode.HeartBeatUpdateError, ex);
throw;
}
}
Thread 2: Individual entity update thread when called:
context.AttachTo(tablename, individual entity, "*");
With Thread 2, it is very much possible that you may receive “The context is not currently tracking the entity” error because you don’t have entities ETag in the memory.
The best practice is to handle above scenario is to:
- Always use .AttachTo() if you are using “*” as an ETag or keeping track of the actual ETag
- When you are writing conditional update process, you’ll need the ETag