I have a small, simple C# application which updates an icon in the system tray. I use it to graphically show the CPU usage. The application works great. I keep the Window hidden and don't show it in the taskbar so it doesn't get in the way.
My issue is that it will run great for a while. Often several hours. But then it will mysteriously quit. No warnings. Nothing. The icon is just gone and the program is no longer running. I have tested the program in the debugger under varying conditions, so I don't think that is it. Is there something obvious I am missing? If the program encounters an error and quits should I be expecting a message if the Form is hidden? Is there some "keep-alive" message or something that I need to handle?
Here is the relevant section of code:
public Form1()
{
InitializeComponent();
trayIcon = new NotifyIcon();
trayIcon.Text = "CPU Utilization";
trayIcon.Icon = new Icon(SystemIcons.Application, 40, 40);
trayIcon.Visible = true;
update = new Thread(new ThreadStart(UpdateCPU));
update.Start();
}
protected override void OnLoad(EventArgs e)
{
Visible = false;
ShowInTaskbar = false;
base.OnLoad(e);
}
private void UpdateCPU()
{
Bitmap bm = new Bitmap(32, 32);
Graphics g = Graphics.FromImage(bm);
while (true)
{
g.FillRectangle(new SolidBrush(c3), 17, 17, 15, 15);
trayIcon.Icon = System.Drawing.Icon.FromHandle(bm.GetHicon());
Thread.Sleep(1000);
}
}
Any help would be greatly appreciated!
I would suggest you add an Unhandled Exception Handler
Global Exception Handling for winforms control
An Exception is likely being thrown, causing your program to exit.
Then, introduce logging to log what the Exception was. Personally I prefer NLog.
I'm a bit surprised that you can update trayIcon from a non-UI thread without receiving a cross-thread exception.