Created
May 2, 2014 13:44
-
-
Save chgeuer/248680c804f2f62f424a to your computer and use it in GitHub Desktop.
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
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