// (c) 2007 Richard Grimes // www.grimes.demon.co.uk using System; using System.Diagnostics; class Server { const string catName = "Data Generator"; const string catHelp = "Generates random sample data"; const string ctrName = "# Connected Clients"; const string ctrHelp = "The number of clients connected to the server"; static PerformanceCounter clients; static void Main(string[] args) { if (args.Length > 0) { // Delete category if (PerformanceCounterCategory.Exists(catName)) { PerformanceCounterCategory.Delete(catName); } return; } if (!PerformanceCounterCategory.Exists(catName)) { // Create new counter if it does not exist CounterCreationDataCollection ccdc = new CounterCreationDataCollection(); CounterCreationData ccd = new CounterCreationData(ctrName, ctrHelp, PerformanceCounterType.NumberOfItems32); ccdc.Add(ccd); PerformanceCounterCategory.Create( catName, catHelp, PerformanceCounterCategoryType.SingleInstance, ccdc); Console.WriteLine("Category created, re-run the application"); return; } Console.CancelKeyPress += CtrlCHandler; // Provide counters clients = new PerformanceCounter(catName, ctrName, false); Random rand = new Random(Environment.TickCount); int numberOfClients = 5; Console.WriteLine("Press Ctrl-C to end the server"); while (true) { // Simulate clients attaching and detaching int val = rand.Next(100); if (val > 66) numberOfClients++; if (val < 33) numberOfClients--; if (numberOfClients < 0) numberOfClients = 0; clients.RawValue = numberOfClients; System.Threading.Thread.Sleep(100); } } static void CtrlCHandler(object o, ConsoleCancelEventArgs a) { if (clients != null) clients.Close(); Console.WriteLine("Finished"); } }