I have a requirement where I have to update different columns of the same row in azure table which is accessed by multiple threads simultaneously (all querying for the same row) without overwriting what the other thread would have updated. Sample code:
public void doSomething(){
List<string> records= new List<string>();
for (var j = 0; j < 12; j++)
{
InsertRecords(j);//Inserts data to the table and Creates a variable Ids=PartitionKey+rowkey
records.Add(Ids);//It has all 12 partitionKeys and RowKeys combinations
}
for (var i = 0; i < 12;i+=4)
{
List<Task> tasks = new List<Task>();
tasks.Add(Task.Run(() => {
UpdateTable("COl1",records[i]); }));//should update col1 to complete
tasks.Add(Task.Run(() => {
UpdateTable("Col2",records[i]); }));
tasks.Add(Task.Run(() => {
UpdateTable("Col3",records[i]); }));
tasks.Add(Task.Run(() => {
UpdateTable("Col4",records[i]); }));
Task.WaitAll(tasks.ToArray());
}
}
public void UpdateTable(String message){
ITableEntity entity = myRepo.retrieveEntity(myPartitionKey, myRowKey);
If (message=="COL1"){
//Update Col1 to Complete
(myClass)entity).Col= "Complete";
}
If (message=="COL2"){
//Update Col2 to Complete
(myClass)entity).Col2= "Complete";
}
If (message=="COL3"){
//Update Col3 to Complete
(myClass)entity).Col3= "Complete";
}
TableOperation tableOp=TableOperation.InsertOrReplace(entity);
//var mergeOperation = TableOperation.Merge(entity); tried this also but didnt work
// myTable.Execute(mergeOperation);
CloudStorageAccount storageAccount = CloudStorageAccount.Parse("ConnString");
CloudTableClient tableClient=storageAccount.CreateCloudTableClient();
myTable = tableClient.GetTableReference("MyTable");
myTable.CreateIfNotExists();
myTable.Execute(tableOp);//doesn't seem to work[overwrites]
}
expected output: COl1,Col2,Col3 should have status "complete". How to achieve this?