Created
December 7, 2012 21:52
-
-
Save fernandoacorreia/4236819 to your computer and use it in GitHub Desktop.
Asynchronous insert in Azure Tables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Data.Services.Client; | |
using System.Diagnostics; | |
using System.Net; | |
using System.Threading; | |
using Microsoft.WindowsAzure; | |
using Microsoft.WindowsAzure.ServiceRuntime; | |
using Microsoft.WindowsAzure.StorageClient; | |
namespace WorkerRole1 | |
{ | |
public class WorkerRole : RoleEntryPoint | |
{ | |
public override void Run() | |
{ | |
var storageWriter = new TableStorageWriter(); | |
while (true) | |
{ | |
Thread.Sleep(10000); | |
storageWriter.Write("Working..."); | |
} | |
} | |
public override bool OnStart() | |
{ | |
ServicePointManager.DefaultConnectionLimit = 12; | |
return base.OnStart(); | |
} | |
} | |
internal class TableStorageWriter | |
{ | |
private const string _tableName = "StorageTest"; | |
private readonly CloudStorageAccount _storageAccount; | |
private readonly CloudTableClient _tableClient; | |
public TableStorageWriter() | |
{ | |
_storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString")); | |
_tableClient = _storageAccount.CreateCloudTableClient(); | |
_tableClient.CreateTableIfNotExist(_tableName); | |
} | |
public void Write(string message) | |
{ | |
try | |
{ | |
DateTime now = DateTime.UtcNow; | |
var entity = new StorageTestEntity | |
{ | |
Message = message, | |
PartitionKey = string.Format("{0:yyyy-MM-dd}", now), | |
RowKey = string.Format("{0:HH:mm:ss.fff}-{1}", now, Guid.NewGuid()) | |
}; | |
TableServiceContext context = _tableClient.GetDataServiceContext(); | |
context.AddObject(_tableName, entity); | |
context.BeginSaveChangesWithRetries(SaveChangesOptions.Batch, | |
(asyncResult => context.EndSaveChangesWithRetries(asyncResult)), | |
null); | |
} | |
catch (StorageClientException e) | |
{ | |
Debug.WriteLine("Error: {0}", e.Message); | |
Debug.WriteLine("Extended error info: {0} : {1}", | |
e.ExtendedErrorInformation.ErrorCode, | |
e.ExtendedErrorInformation.ErrorMessage); | |
} | |
} | |
} | |
internal class StorageTestEntity : TableServiceEntity | |
{ | |
public string Message { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment