通过多个线程同时更新AZURE表中同一行的不同列

时间:2018-08-28 08:18:03

标签: c# concurrency azure-table-storage azure-tablequery

我有一个要求,我必须更新azure表中同一行的不同列,该表必须由多个线程同时访问(所有查询同一行),而不覆盖其他线程将要更新的内容。  示例代码

*enter image description here*

   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]
        }

预期输出:COl1,Col2,Col3的状态应为“完成”。如何实现呢?

0 个答案:

没有答案