Created
December 8, 2012 14:02
-
-
Save fernandoacorreia/4240371 to your computer and use it in GitHub Desktop.
Asynchronous insert in Azure Tables (complete example)
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.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("Messages"); | |
while (true) | |
{ | |
storageWriter.Write(new MessageEntity("Working")); | |
Thread.Sleep(10000); | |
} | |
} | |
public override bool OnStart() | |
{ | |
ServicePointManager.DefaultConnectionLimit = 12; | |
return base.OnStart(); | |
} | |
} | |
internal class TableStorageWriter | |
{ | |
private readonly CloudStorageAccount _storageAccount; | |
private readonly CloudTableClient _tableClient; | |
private readonly string _tableName; | |
public TableStorageWriter(string tableName) | |
{ | |
_tableName = tableName; | |
_storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString")); | |
_tableClient = _storageAccount.CreateCloudTableClient(); | |
_tableClient.CreateTableIfNotExist(_tableName); | |
} | |
public void Write(TableServiceEntity entity) | |
{ | |
TableServiceContext context = _tableClient.GetDataServiceContext(); | |
context.AddObject(_tableName, entity); | |
context.BeginSaveChangesWithRetries((asyncResult => context.EndSaveChangesWithRetries(asyncResult)), null); | |
} | |
} | |
internal sealed class MessageEntity : TableServiceEntity | |
{ | |
public MessageEntity(String message) | |
{ | |
DateTime now = DateTime.UtcNow; | |
PartitionKey = string.Format("{0:yyyy-MM-dd}", now); | |
RowKey = string.Format("{0:HH:mm:ss.fff}-{1}", now, Guid.NewGuid()); | |
Message = message; | |
} | |
public string Message { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment