Files
csharp/examples/watch/Program.cs
Qing Long 6d27bd900b feat: enhance Kubernetes client with watch functionality (#1667)
* feat: enhance Kubernetes client with watch functionality

* refactor: simplify watch event handling in Kubernetes client example

* refactor: update Kubernetes watch functionality to use new event handling methods and add async enumerable support

* fix

* fix

* fix: correct usage of Pod list items in client example and update Obsolete attribute formatting

* fix: update client example to use correct Pod list method and improve Obsolete attribute formatting

* refactor: enhance type resolution for list items in TypeHelper by adding TryGetItemTypeFromSchema method

* feat: mark Watch methods as obsolete to prepare for future deprecation

* fix

* refactor: update WatcherExt class to internal and remove obsolete attributes; improve example method signature in Program.cs

* refactor: change WatcherExt class from internal to public and mark methods as obsolete for future deprecation
2025-10-11 15:10:53 -07:00

39 lines
1.3 KiB
C#

using k8s;
using System;
using System.Threading;
using System.Threading.Tasks;
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
IKubernetes client = new Kubernetes(config);
var podlistResp = client.CoreV1.WatchListNamespacedPodAsync("default");
// C# 8 required https://docs.microsoft.com/en-us/archive/msdn-magazine/2019/november/csharp-iterating-with-async-enumerables-in-csharp-8
await foreach (var (type, item) in podlistResp.ConfigureAwait(false))
{
Console.WriteLine("==on watch event==");
Console.WriteLine(type);
Console.WriteLine(item.Metadata.Name);
Console.WriteLine("==on watch event==");
}
#pragma warning disable CS8321 // Remove unused private members
void WatchUsingCallback(IKubernetes client)
#pragma warning restore CS8321 // Remove unused private members
{
using (var podlistResp = client.CoreV1.WatchListNamespacedPod("default", onEvent: (type, item) =>
{
Console.WriteLine("==on watch event==");
Console.WriteLine(type);
Console.WriteLine(item.Metadata.Name);
Console.WriteLine("==on watch event==");
}))
{
Console.WriteLine("press ctrl + c to stop watching");
var ctrlc = new ManualResetEventSlim(false);
Console.CancelKeyPress += (sender, eventArgs) => ctrlc.Set();
ctrlc.Wait();
}
}