forked from temporalio/samples-dotnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
78 lines (69 loc) · 2.32 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
using Microsoft.Extensions.Logging;
using Temporalio.Client;
using Temporalio.Exceptions;
using Temporalio.Worker;
using TemporalioSamples.ActivityHeartbeatingCancellation;
// Create a client to localhost on default namespace
var client = await TemporalClient.ConnectAsync(new("localhost:7233")
{
LoggerFactory = LoggerFactory.Create(builder =>
builder.
AddSimpleConsole(options => options.TimestampFormat = "[HH:mm:ss] ").
SetMinimumLevel(LogLevel.Information)),
});
async Task RunWorkerAsync()
{
// Cancellation token cancelled on ctrl+c
using var tokenSource = new CancellationTokenSource();
Console.CancelKeyPress += (_, eventArgs) =>
{
tokenSource.Cancel();
eventArgs.Cancel = true;
};
// Run worker until cancelled
Console.WriteLine("Running worker");
using var worker = new TemporalWorker(
client,
new TemporalWorkerOptions(taskQueue: "activity-heartbeating-cancellation-sample")
.AddActivity(MyActivities.FakeProgressAsync)
.AddWorkflow<MyWorkflow>());
try
{
await worker.ExecuteAsync(tokenSource.Token);
}
catch (OperationCanceledException)
{
Console.WriteLine("Worker cancelled");
}
}
async Task ExecuteWorkflowAndThenCancelAsync()
{
Console.WriteLine("Executing workflow");
var handle = await client.StartWorkflowAsync(
(MyWorkflow wf) => wf.RunAsync(),
new(id: "activity-heartbeating-cancellation-workflow-id", taskQueue: "activity-heartbeating-cancellation-sample"));
// Simulate waiting for some time.
// Cancel may be immediately called, waiting is not needed
await Task.Delay(TimeSpan.FromSeconds(20));
await handle.CancelAsync();
Console.WriteLine("Cancelled workflow successfully");
try
{
await handle.GetResultAsync();
}
catch (WorkflowFailedException e) when (e.InnerException is CanceledFailureException)
{
Console.WriteLine("await handle.GetResultAsync() threw because Workflow was cancelled");
}
}
switch (args.ElementAtOrDefault(0))
{
case "worker":
await RunWorkerAsync();
break;
case "workflow":
await ExecuteWorkflowAndThenCancelAsync();
break;
default:
throw new ArgumentException("Must pass 'worker' or 'workflow' as the single argument");
}