Java ใช้ `System.exit(0)` หยุด JVM ทันที ใน C# ใช้ Environment.Exit()
Basic Usage
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("Starting...");
// จบโปรแกรมทันที คืน Exit Code 0 (Success)
Environment.Exit(0);
Console.WriteLine("This won't print");
}
}
Exit Codes มาตรฐาน
| Exit Code | ความหมาย | ใช้เมื่อไหร่ |
| 0 | Success | โปรแกรมทำงานเสร็จสมบูรณ์ |
| 1 | General Error | Error ไม่เฉพาะเจาะจง |
| 2 | File Not Found / Invalid Format | Config ไม่พบ, Input ไม่ถูกต้อง |
| 3-127 | Application Specific | กำหนดเองตาม Domain |
| 128+ | Signal/OS Specific | Unix Signals (SIGTERM=143, etc.) |
ตัวอย่าง: Exit Codes แบบมีความหมาย
public class Program
{
public static int Main(string[] args)
{
try
{
if (args.Length == 0)
{
Console.Error.WriteLine("Error: No input file specified");
return 2; // Invalid Arguments
}
string filePath = args[0];
if (!File.Exists(filePath))
{
Console.Error.WriteLine($"Error: File not found: {filePath}");
return 3; // File Not Found
}
var content = File.ReadAllText(filePath);
ProcessContent(content);
return 0; // Success
}
catch (UnauthorizedAccessException)
{
Console.Error.WriteLine("Error: Permission denied");
return 4; // Permission Denied
}
catch (Exception ex)
{
Console.Error.WriteLine($"Error: {ex.Message}");
return 1; // General Error
}
}
static void ProcessContent(string content) { }
}
Environment.Exit vs Return from Main
| ด้าน | Environment.Exit(code) | Return from Main |
| Scope | จบ Process ทันที (ทุก Thread) | จบ Main Thread เท่านั้น |
| Finally Blocks | ไม่รัน (Process Terminated) | รันปกติ |
| Destructors/Finalizers | ไม่รัน | รัน (ใน GC) |
| Static Constructors | ไม่รันสำหรับ Types ที่ยังไม่ Load | รันปกติ |
| ใช้เมื่อ | Critical Error, Hosted Environment | Normal Exit |
⚠️ ข้อควรระวัง
Environment.Exit() เรียก ExitProcess (Windows) / _exit (Unix) - ไม่รัน Finally/Using/Dispose
- ใน ASP.NET Core / Generic Host: ควรใช้
IHostApplicationLifetime.StopApplication() แทน
- ใน WPF/WinForms: ควรใช้
Application.Shutdown()
- Unit Test: อย่าใช้ Environment.Exit (จะ Kill Test Runner) ใช้ Return Code หรือ Throw Exception
Graceful Shutdown Pattern
public class App
{
private readonly IHost _host;
public async Task RunAsync(string[] args)
{
try
{
await _host.StartAsync();
await _host.WaitForShutdownAsync();
}
finally
{
await _host.StopAsync(TimeSpan.FromSeconds(30));
}
}
}