I need a simple example of how to run a background task in my .Net Framework 4.7.2 Console App Windows Service. I know how to do it in .Net Core, but I have an interim application that cannot be upgraded. Thus, I have to find a quick and dirty solution.
The background task I want to run is this (the Update() method):
public class UpdateBackgroundTask
{
private readonly Settings _settings;
public UpdateBackgroundTask(Settings settings)
{
_settings = settings;
}
public void Update()
{
//first, check the current version and see if it is the same
//if it is, run away
var currentVersion = new Version(GetVersion());
//version will be retrieved from the file system somehow...no need to worry about these details
string version = GetVersionFromFileSystem(); //this method is not in this example
var newVersion = new Version(version);
if (!currentVersion.Equals(newVersion))
{
try
{
//fire off a powershell process to update the current running service
}
catch (Exception ex)
{
//do any error handling
}
}
}
public string GetVersion()
{
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
FileVersionInfo fileVersion = FileVersionInfo.GetVersionInfo(assembly.Location);
return fileVersion.FileVersion;
}
}
How would I wire this up in the Windows service interface start event handler, OnStart?