Created
January 17, 2024 16:46
-
-
Save ReubenBond/8dc47f68634faafe334fadc6f5444ad0 to your computer and use it in GitHub Desktop.
Orleans Grain Long Running Reminder
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
#nullable enable | |
using Orleans.Runtime; | |
namespace MyGrains; | |
public class MyLongRunningReminderGrain : Grain, IRemindable | |
{ | |
private readonly CancellationTokenSource _shutdownCancellation = new(); | |
private Task? _backgroundTask; | |
public Task ReceiveReminder(string reminderName, TickStatus status) | |
{ | |
if (_backgroundTask is null or { IsCompleted: true }) | |
{ | |
_backgroundTask = ProcessBackgroundTask(); | |
} | |
return Task.CompletedTask; | |
} | |
private async Task ProcessBackgroundTask() | |
{ | |
// It's polite to yield immediately, since we're starting background work. | |
await Task.Yield(); | |
while (!_shutdownCancellation.IsCancellationRequested) | |
{ | |
// Do work here... | |
await Task.Delay(1_000); | |
} | |
} | |
public override async Task OnDeactivateAsync(DeactivationReason reason, CancellationToken cancellationToken) | |
{ | |
_shutdownCancellation.Cancel(); | |
if (_backgroundTask is { } task && !task.IsCompleted) | |
{ | |
// Wait for the background task to complete, but don't wait indefinitely. | |
await task.WaitAsync(cancellationToken); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment