GcMemoryAllocationTest
/
Program.cs
107 строк · 2.7 Кб
1PrintHelp();2
3List<string> list1 = new List<string>();4List<string> list2 = new List<string>();5List<string> list3 = new List<string>();6List<string> list4 = new List<string>();7CancellationTokenSource cts = new CancellationTokenSource();8
9void AddStringsToList(List<string> list)10{
11while (true)12{13if (cts.Token.IsCancellationRequested)14break;15
16list.Add($"String added at {DateTime.Now}");17}18}
19
20void ClearList(List<string> list)21{
22list.Clear();23list.TrimExcess();24}
25
26void PrintHelp()27{
28Console.WriteLine("=== Application Help ===");29Console.WriteLine("Available commands:");30Console.WriteLine("start - Start adding strings to the lists.");31Console.WriteLine("stop - Stop adding strings to the lists and exit the application.");32Console.WriteLine("continue - The tasks are already running.");33Console.WriteLine("clear - Clear all the lists.");34Console.WriteLine("gc - Call the garbage collector.");35Console.WriteLine("help - Display this help message.");36Console.WriteLine("========================");37}
38
39var isStarted = false;40var tasks = new List<Task>();41
42while (true)43{
44string? input = Console.ReadLine();45
46if (input == "start")47{48if (isStarted)49{50Console.WriteLine("The tasks are already running.");51continue;52}53
54cts = new CancellationTokenSource();55tasks.Add(Task.Run(() => AddStringsToList(list1), cts.Token));56tasks.Add(Task.Run(() => AddStringsToList(list2), cts.Token));57tasks.Add(Task.Run(() => AddStringsToList(list3), cts.Token));58tasks.Add(Task.Run(() => AddStringsToList(list4), cts.Token));59
60isStarted = true;61Console.WriteLine("Tasks started.");62}63else if (input == "stop")64{65if (!isStarted)66{67Console.WriteLine("The tasks are not running.");68continue;69}70
71cts.Cancel();72await Task.WhenAll(tasks);73isStarted = false;74Console.WriteLine("Tasks stopped.");75}76else if (input == "clear")77{78if (isStarted)79{80Console.WriteLine("Stop tasks before clearing.");81continue;82}83
84ClearList(list1);85ClearList(list2);86ClearList(list3);87ClearList(list4);88
89Console.WriteLine("Lists cleared.");90}91else if (input == "gc")92{93GC.Collect();94GC.WaitForPendingFinalizers();95Console.WriteLine("Garbage collector called.");96}97else if (input == "exit")98{99break;100}101else if (input == "help")102{103PrintHelp();104}105}
106
107Console.WriteLine("Testing has been finished. Press any key to exit ...");108