Skip to content

Instantly share code, notes, and snippets.

@chgeuer
Created May 2, 2014 13:44
Show Gist options
  • Save chgeuer/248680c804f2f62f424a to your computer and use it in GitHub Desktop.
Save chgeuer/248680c804f2f62f424a to your computer and use it in GitHub Desktop.
namespace MyGrainCollection
{
using MyGrainInterfaces;
using Orleans;
using System;
using System.Threading.Tasks;
// [StorageProvider(ProviderName = "AzureTableStorage")]
[StorageProvider(ProviderName = "BlobStorageProvider")]
public class LobbyGrain : GrainBase<ILobbyGrainState>, ILobbyGrain
{
private readonly PersistencyPolicy policy = PersistencyPolicy.Every(TimeSpan.FromSeconds(10));
async Task<string> ILobbyGrain.GetQuote()
{
this.State.Value++;
Action log = ((Func<Action>)(() =>
{
var logger = this.GetLogger();
var id = this.GetPrimaryKey();
return () => logger.Info("Persisted state in grain \"{0}\"", id);
}))();
await this.policy.PersistIdNeeded(
persist: this.State.WriteStateAsync,
otherAction: log);
return (this.State.Value).ToString();
}
}
public class PersistencyPolicy
{
public static PersistencyPolicy Every(TimeSpan interval)
{
return new PersistencyPolicy(interval);
}
public PersistencyPolicy(TimeSpan interval)
{
this.Interval = interval;
}
private TimeSpan Interval { get; set; }
private DateTimeOffset Last { get; set; }
private bool ShouldPersist { get { return DateTimeOffset.UtcNow > this.Last.Add(this.Interval); } }
public async Task PersistIdNeeded(Func<Task> persist, Action otherAction = null)
{
if (ShouldPersist)
{
await persist();
this.Last = DateTimeOffset.UtcNow;
if (otherAction != null)
{
otherAction();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment