0

I'm new at c# development. My goal is to send a toast notification in background (by using Windows Services) alter some petiod of time. Program.cs file:

static class Program {
    static void Main() {
        try {
            ServiceBase[] servicesToRun = {
                new TestService()
            };

            ServiceBase.Run(servicesToRun);
            Notifications notifications = new Notifications();
            notifications.Start();

            var notive = new ToastContentBuilder();
            notive.AddText("Notification");
            notive.Show();
        }
        catch (Exception e) {
            Logger.WriteLine("Unhandled exception: " + e.Message);
        }
    }
}

and Notification file:

public class Notifications
   {
    private readonly Timer _timer;

    public Notifications()
    {
        _timer = new Timer(1000 * 10) { 
        AutoReset = true};
        _timer.Elapsed += TimerElapsed;
    }

    private void TimerElapsed(object sender, ElapsedEventArgs e)
    {
        var notive = new ToastContentBuilder();
        notive.AddText("Notification2");
        notive.Show();
    }

    public void Start()
    {
        _timer.Start();
    } 

    public void Stop()
    {
        _timer?.Stop();
    }
}

When I use cmd command 'TestService.exe start', I can see 'Notification', but 'Notification2' that should be sended every 10 sec, does not appear. Also adding code:

string[] lines = new string[] { DateTime.Now.ToString() };
            File.AppendAllLines(@"C:\Visual Studio WorkPlace\License.txt", lines);

before creating toast 'Notification2' will work. I suppose that can be because toast 'Notification2' doesn't appear in Main Thread.

Neelami
  • 13
  • 4
  • Does this answer your question? [Windows service with timer](https://stackoverflow.com/questions/12885013/windows-service-with-timer) – Code Name Jack Oct 11 '22 at 08:33
  • It seems like Main method exits before it gets a chance to show the Notification2? – Sasha Oct 11 '22 at 08:35

1 Answers1

0

In case you are using dotnet core, You can use Background Service with a timer,

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-3.1&tabs=visual-studio#timed-background-tasks.

Otherwise you can use a timer in Windows service. And use the start and stop method of the Service to control the timer.

Explained here, Windows service with timer

Code Name Jack
  • 2,856
  • 24
  • 40
  • thank u for sharing the links, I have tried to use the same pattern, unfortunately doesn't help. Can it be because I can use toast only in MainThread? – Neelami Oct 12 '22 at 11:20