I have an ASP.Net Core application that runs as Windows Service. Its task is to check files on the FTP server when the condition is met is to launch the WPF application.
The application works properly during tests in the debugger. When it is started as a service it starts but does not start WPF.
public class AplicationInstance: SingletonExtension<AplicationInstance>
{
public SessionOptions FTPSessionOptions { get; set; }
public string FTPFingerprint { get; set; }
public List<FileModel> CurrentFiles;
public List<FileModel> OldFiles;
public ObservableCollection<FileModel> DifrentFiles;
private AplicationInstance()
{
CurrentFiles = new List<FileModel>();
OldFiles = new List<FileModel>();
DifrentFiles = new ObservableCollection<FileModel>();
StartNewAplicationThread();
Task.Delay(1000).Wait();
}
public Application app { get; set; }
public void DispatchToApp(Action action)
{
app.Dispatcher.Invoke(action);
}
[STAThread]
private void StartNewAplicationThread()
{
var appthread = new Thread(new ThreadStart(() =>
{
try
{
app = new Application();
app.ShutdownMode = ShutdownMode.OnExplicitShutdown;
app.Run();
}
catch (Exception ex)
{
var t = ex.Message; ;
}
}));
appthread.SetApartmentState(ApartmentState.STA);
appthread.Start();
appthread.Name = "NSP Files -> All File Browser " + DateTime.Now;
}
}
private static void StartWpfWindows()
{
WPFStartModel _newWPFApplication = new WPFStartModel();
_newWPFApplication.Title = "xxx";
_newWPFApplication.Files = AplicationInstance.Instance.CurrentFiles;
AplicationInstance.Instance.DispatchToApp(() =>
{
appWindow = new WPFAplication.FileListWindow(_newWPFApplication);
appWindow.Show();
});
}
EDIT (answer first 2 comments): The problem occurs in the built version (Release) I have an additional application that adds a new Windows Service and starts it, all through CMD.
public static async Task<string> ExecuteCommand(string command, int timeMiliseconds = 0)
{
try
{
System.Diagnostics.ProcessStartInfo procStartInfo =
new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = false;
procStartInfo.Verb = "runas";
Console.WriteLine(command);
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
proc.WaitForExit();
if (!proc.HasExited)
{
if (timeMiliseconds != 0)
await Task.Delay(timeMiliseconds);
else
await Task.Delay(400);
}
string result = proc.StandardOutput.ReadToEnd();
if (!string.IsNullOrEmpty(result))
{
return result;
}
else return string.Empty;
}
catch (Exception objException)
{
Console.WriteLine("CMD EXCEPTION: " + objException.Message);
return string.Empty;
}
}
I use command:
string _tmpCommand = "sc create " + ServiceName + " binPath= \"" + ServicePath + "\"";
//And
string _tmpCommand = "sc start " + ServiceName;
I build app with this command: "dotnet publish -c Release -r win10-x64"