Question: A form should open only when there is an event if there is no event it should not display on the screen. So Basically i thought of using a timer to do this. An exe will continously be running and after every minute it checks the db to see if there is data and if there is it shows up on the screen and will only be closed manually with user interaction. After a minute it checks again and displays the form if Data is present in the DB.

I used system.threading.Timer in Program.cs file to open a window after every minute.Below is the code

```
timer = new System.Threading.Timer((s) => { 
  EL.CustomMessageBox l = new EL.CustomMessageBox(); 
  l.ShowDialog();                
}, null, TimeSpan.Zero, 60000);

```

After certain time I see that this exe is still running in the taskmanager but even though there is data in the DB it stops showing up on the screen. Any help is appreciated.

Answer: 
`System.Threading.Timer` runs its callback on a threadpool thread. You should never use a threadpool thread for UI work, because:

1. They don't run a message dispatch loop.
2. You don't control when the thread gets recycled. UI windows have thread affinity and if their thread exits all the associated windows go poof immediately (you won't even get `WM_DESTROY` messages).

A normal `Application.Run` loop on the main thread, with a hidden main window and a UI timer will serve you much better.
You should call `Invoke` to execute your delegate on the thread that owns the control's underlying window handle.

Something like this should work:

```
timer = new System.Threading.Timer((s) => { 
  EL.CustomMessageBox l = new EL.CustomMessageBox(); 
  l.Invoke((Action) () => 
  {
    l.ShowDialog();
  });               
}, null, TimeSpan.Zero, 60000);

```

Or even better, use this extension method:

```
public static void InvokeIfRequired(this Control c, MethodInvoker action)
{
    if (c.InvokeRequired)
    {
        c.Invoke(action);
    }
    else
    {
        action();
    }
}

```

And call it like this:

```
l.InvokeIfRequired(() => { l.ShowDialog(); });

```

Further information can be found at: <https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-make-thread-safe-calls-to-windows-forms-controls?view=netframeworkdesktop-4.8>