I have a WPF app and a Console App (.NET). After publishing the Console app, it will be installed and run as a windows service. This service will check periodically for new messages from an API. If there are new messages, it will start the WPF app to display the messages on the UI. The issue I’m encountering is that when the service is running, I can see the WPF app runs but only in the background. It does not initialize the UI. I followed the solution here but it still does not work for me. Here is the code for my Console app:
Program.cs:
using My_Service_App.Services;
using System.ServiceProcess;
using Topshelf;
namespace My_Service_App
{
class Program
{
static void Main(string[] args)
{
var exitCode = HostFactory.Run(x =>
{
x.Service<WindowsService>(s =>
{
s.ConstructUsing(serv => new WindowsService());
s.WhenStarted(serv => serv.Start());
s.WhenStopped(serv => serv.Stop());
});
x.RunAsLocalSystem();
x.SetServiceName("MyService");
x.SetDisplayName("My Service");
x.SetDescription("My Notification Receiver");
});
}
}
}
WindowService.cs:
public class WindowsService
{
private readonly System.Timers.Timer _timer;
private CancellationTokenSource cancellationTokenSource;
public WindowsService()
{
int interval = 1000 * 60 * 10; // (10 minutes)
_timer = new System.Timers.Timer(interval) { AutoReset = true };
_timer.Elapsed += timer_Elapsed;
cancellationTokenSource = new CancellationTokenSource();
Task task = PollMessages(cancellationTokenSource.Token);
}
private void timer_Elapsed(object? sender, ElapsedEventArgs e)
{
// Start polling messages
cancellationTokenSource = new CancellationTokenSource();
Task.Run(() => PollMessages(cancellationTokenSource.Token));
}
private async Task PollMessages(CancellationToken token)
{
// Fetch messages from API
// Then, start WPF app if there are new messages
string wpfAppPath = ProgramHelpers.GetAppPath();
if (!IsAppRunning("AppName"))
{
Process.Start(wpfAppPath, "NewMessage");
}
}
catch (Exception) { }
}
public void Start()
{
_timer.Start();
}
public void Stop()
{
_timer.Stop();
}
public static bool IsAppRunning(string windowTitle)
{
Process[] processes = Process.GetProcesses();
foreach (Process process in processes)
{
if (process.MainWindowTitle == windowTitle)
{
return true;
}
}
return false;
}