master
md 96 lines 3.01 KB
Rendered Raw
1 # End-to-End Example
2
3 The example below shows one full lifecycle matching the C API example:
4
5 1. Check prerequisites
6 2. Print SDK version
7 3. Create a session (4 CPUs, 4 GB RAM)
8 4. Pull alpine:latest
9 5. Configure an init process (`/bin/echo "Hello from WSL Container!"`)
10 6. Create and start the container
11 7. Wait for the init process to exit
12 8. Print exit code
13 9. Stop and delete the container
14 10. Terminate the session
15
16 ```csharp
17 using Microsoft.WSL.Containers;
18 using System;
19 using System.Text;
20 using System.Threading.Tasks;
21
22 class Program
23 {
24 static async Task<int> Main()
25 {
26 // 0. Check prerequisites
27 var missing = WslcService.GetMissingComponents();
28 if (missing.Count > 0)
29 {
30 Console.WriteLine("WSL components are missing. Run: wsl --install");
31 return 1;
32 }
33
34 var ver = WslcService.GetVersion();
35 Console.WriteLine($"WSL version: {ver.Major}.{ver.Minor}.{ver.Revision}");
36
37 // 1. Create a session
38 var sessionSettings = new SessionSettings("MyApp", @"C:\WslcData")
39 {
40 CpuCount = 4,
41 MemorySizeInMB = 4096
42 };
43
44 var session = new Session(sessionSettings);
45 session.Start();
46
47 // 2. Pull an image
48 var pullOp = session.PullImageAsync(new PullImageOptions("docker.io/library/alpine:latest"));
49 pullOp.Progress = (op, progress) =>
50 Console.WriteLine($"Pull: {progress.Status} {progress.CurrentBytes}/{progress.TotalBytes}");
51 await pullOp;
52
53 // 3. Configure an init process
54 var initProcSettings = new ProcessSettings
55 {
56 CommandLine = new[] { "/bin/echo", "Hello from WSL Container!" },
57 OutputMode = ProcessOutputMode.Event
58 };
59
60 // 4. Configure and create a container
61 var containerSettings = new ContainerSettings("alpine:latest")
62 {
63 Name = "hello-container",
64 InitProcess = initProcSettings
65 };
66
67 var container = session.CreateContainer(containerSettings);
68
69 // 5. Subscribe to init process events before starting
70 var exited = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
71
72 container.InitProcess.OutputReceived += data =>
73 Console.Write(Encoding.UTF8.GetString(data));
74 container.InitProcess.Exited += code =>
75 exited.TrySetResult(code);
76
77 // 6. Start the container
78 container.Start();
79
80 // 7. Wait for the init process to exit (30-second timeout)
81 var completed = await Task.WhenAny(exited.Task, Task.Delay(TimeSpan.FromSeconds(30)));
82 int exitCode = completed == exited.Task ? exited.Task.Result : -1;
83 Console.WriteLine($"Process exited with code: {exitCode}");
84
85 // 8. Clean up
86 if (container.State == ContainerState.Running)
87 {
88 container.Stop(Signal.SIGTERM, TimeSpan.FromSeconds(10));
89 }
90 container.Delete(DeleteContainerOption.None);
91 session.Terminate();
92
93 return exitCode;
94 }
95 }
96 ```