Skip to content

Commit 6d90ddb

Browse files
authored
add async foreach example (#715)
1 parent 041f127 commit 6d90ddb

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

examples/watch/Program.cs

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,36 @@
11
using System;
22
using System.Threading;
3+
using System.Threading.Tasks;
34
using k8s;
45
using k8s.Models;
6+
using Microsoft.Rest;
57

68
namespace watch
79
{
810
internal class Program
911
{
10-
private static void Main(string[] args)
12+
private async static Task Main(string[] args)
1113
{
1214
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
1315

1416
IKubernetes client = new Kubernetes(config);
1517

18+
var podlistResp = client.ListNamespacedPodWithHttpMessagesAsync("default", watch: true);
19+
// C# 8 required https://docs.microsoft.com/en-us/archive/msdn-magazine/2019/november/csharp-iterating-with-async-enumerables-in-csharp-8
20+
await foreach (var (type, item) in podlistResp.WatchAsync<V1Pod, V1PodList>())
21+
{
22+
Console.WriteLine("==on watch event==");
23+
Console.WriteLine(type);
24+
Console.WriteLine(item.Metadata.Name);
25+
Console.WriteLine("==on watch event==");
26+
}
27+
28+
// uncomment if you prefer callback api
29+
// WatchUsingCallback(client);
30+
}
31+
32+
private static void WatchUsingCallback(IKubernetes client)
33+
{
1634
var podlistResp = client.ListNamespacedPodWithHttpMessagesAsync("default", watch: true);
1735
using (podlistResp.Watch<V1Pod, V1PodList>((type, item) =>
1836
{

src/KubernetesClient/WatcherExt.cs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,15 @@ public static Watcher<T> Watch<T, L>(
6666
return Watch(Task.FromResult(response), onEvent, onError, onClosed);
6767
}
6868

69+
/// <summary>
70+
/// create an IAsyncEnumerable from a call to api server with watch=true
71+
/// see https://docs.microsoft.com/en-us/archive/msdn-magazine/2019/november/csharp-iterating-with-async-enumerables-in-csharp-8
72+
/// </summary>
73+
/// <typeparam name="T">type of the event object</typeparam>
74+
/// <typeparam name="L">type of the HttpOperationResponse object</typeparam>
75+
/// <param name="responseTask">the api response</param>
76+
/// <param name="onError">a callbak when any exception was caught during watching</param>
77+
/// <returns>IAsyncEnumerable of watch events</returns>
6978
public static IAsyncEnumerable<(WatchEventType, T)> WatchAsync<T, L>(
7079
this Task<HttpOperationResponse<L>> responseTask,
7180
Action<Exception> onError = null)

0 commit comments

Comments
 (0)