Skip to content

Instantly share code, notes, and snippets.

@OlegKarasik
Last active December 5, 2018 13:42
Show Gist options
  • Save OlegKarasik/c7713d7b1f6f38af40c7d92d2436a023 to your computer and use it in GitHub Desktop.
Save OlegKarasik/c7713d7b1f6f38af40c7d92d2436a023 to your computer and use it in GitHub Desktop.
Verify Stateful Service Life Cycle
internal static class Program
{
private static void Main()
{
try
{
ServiceRuntime.RegisterServiceAsync("SlowStatefulServiceType",
context => new SlowStatefulService(context)).GetAwaiter().GetResult();
Thread.Sleep(Timeout.Infinite);
}
catch (Exception e)
{
throw;
}
}
}
public sealed class SlowCommunicationListener : ICommunicationListener
{
public async Task<string> OpenAsync(
CancellationToken cancellationToken)
{
await Task.Delay(10000);
return string.Empty;
}
public async Task CloseAsync(
CancellationToken cancellationToken)
{
await Task.Delay(10000);
}
public void Abort()
{
Thread.Sleep(5000);
}
}
public sealed class SlowStatefulService : StatefulService
{
public SlowStatefulService(
StatefulServiceContext context)
: base(context)
{
}
protected override IEnumerable<ServiceReplicaListener> CreateServiceReplicaListeners()
{
return new ServiceReplicaListener[]
{
new ServiceReplicaListener(serviceContext => new SlowCommunicationListener(), listenOnSecondary: true)
};
}
protected override async Task OnOpenAsync(
ReplicaOpenMode openMode,
CancellationToken cancellationToken)
{
await Task.Delay(10000);
await base.OnOpenAsync(openMode, cancellationToken);
}
protected override async Task OnChangeRoleAsync(
ReplicaRole newRole,
CancellationToken cancellationToken)
{
await Task.Delay(10000);
await base.OnChangeRoleAsync(newRole, cancellationToken);
}
protected override async Task RunAsync(
CancellationToken cancellationToken)
{
for (; ; )
{
if (cancellationToken.IsCancellationRequested)
{
break;
}
Thread.Sleep(100);
}
await Task.Delay(10000);
await base.RunAsync(cancellationToken);
}
protected override async Task OnCloseAsync(
CancellationToken cancellationToken)
{
await Task.Delay(10000);
await base.OnCloseAsync(cancellationToken);
}
protected override void OnAbort()
{
base.OnAbort();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment