更新(2014年3月20日美国东部时间下午5:11):添加了代码以写入“GotHere0.txt”。 Gothere0,1,2,3都显得很好。 Gothere4没有出现。
请注意 - 这不是重复 - 它与我找到的所有现有主题有非常微妙的差异。
要求:
到目前为止的结果:
Process.Start(sInfo)完成,好像一切都成功了。没有异常被抛出。 <处理ID>返回0。但是,显然testapp.exe中的代码实际上没有执行。有谁知道我怎么解决这个问题?谢谢!
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading.Tasks;
namespace TestService
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
System.IO.File.WriteAllText(@"c:\temp\GotHere0.txt", "");
System.Threading.Tasks.Task.Factory.StartNew(() => Run(), TaskCreationOptions.LongRunning);
}
protected override void OnStop()
{
ContinueRunning = false;
}
public static bool ContinueRunning = true;
public void Run()
{
System.IO.File.WriteAllText(@"c:\temp\GotHere1.txt", "");
while (ContinueRunning)
{
try
{
List<string> args = new List<string>();
args.Add("Test");
StartApp(@"c:\temp\testapp.exe", args);
}
catch (Exception)
{ }
if (ExitEarly()) return;
}
}
private static void StartApp(string exePath, List<string> args)
{
try
{
System.IO.File.WriteAllText(@"c:\temp\GotHere2.txt", "");
ProcessStartInfo sInfo = new ProcessStartInfo();
sInfo.FileName = exePath;
sInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(exePath);
sInfo.Arguments = string.Join(" ", args);
sInfo.CreateNoWindow = false;
Process runningProcess = Process.Start(sInfo);
string message = "";
if (runningProcess!=null)
{
message = runningProcess.Id.ToString();
}
System.IO.File.WriteAllText(@"c:\temp\GotHere3.txt", message);
}
catch (Exception exc)
{
System.IO.File.WriteAllText(@"c:\temp\GotHere4.txt", exc.Message);
}
}
private static bool ExitEarly()
{
// Sleep for a total of 60 seconds, and return if "OnStop" is called.
for (int i = 0; i < 600; i++)
{
System.Threading.Thread.Sleep(100);
if (!ContinueRunning) return true;
}
return false;
}
}
}
以下是testapp.exe的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace testapp
{
class Program
{
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder();
if (args == null || args.Length == 0)
{
sb.AppendLine("NO arguments were passed.");
}
else
{
foreach (string arg in args)
{
sb.AppendLine("Arg: [" + arg + "]");
}
}
System.IO.File.WriteAllText("helloworld.txt", sb.ToString());
}
}
}
答案 0 :(得分:-1)
如果您希望从正在启动的应用程序中看到UI,则不会。您无法从服务启动UI。