我有服务编写C#和Visual Studio 2012以及NetFrameWork 4.5,这是OnStart-event的代码
安装服务后,我尝试启动它,它确实工作了 错误是:
Windows无法在本地计算机上启动DPrintServer服务
错误1053:服务未响应启动或控制请求 及时时尚。
protected override void OnStart(string[] args)
{
string dirx = @"D:\tempsi";
//Directory.SetCurrentDirectory(@"D:\tmp");
Directory.SetCurrentDirectory(dirx);
/*Ini.IniFile ini = new Ini.IniFile("PrintServer.ini");
string smtp_server = ini.IniReadValue("smtp", "server");
string from_email = ini.IniReadValue("from", "fromemail");
string to_email = ini.IniReadValue("from", "toemail");
string directory = ini.IniReadValue("settings", "dir");
*/
string smtp_server = ConfigurationSettings.AppSettings.Get("server");
string from_email = ConfigurationSettings.AppSettings.Get("fromemail");
string to_email = ConfigurationSettings.AppSettings.Get("toemail");
string ddirectory = ConfigurationSettings.AppSettings.Get("dir");
string attach_dir = ConfigurationSettings.AppSettings.Get("attachdir");
string filename = ConfigurationSettings.AppSettings.Get("filename");
string subject = ConfigurationSettings.AppSettings.Get("subject");
string mailcontent = ConfigurationSettings.AppSettings.Get("mailcontent");
//string directory = ConfigurationSettings.AppSettings.Get("dir");
/* while(true)
{*/
int counter = 1;
while (true)
{
//counter++;
if (File.Exists(attach_dir + filename))
{
ProcessStartInfo startInfo = new ProcessStartInfo();
/*startInfo.FileName = "batti.bat";
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
//startInfo.Arguments = file;
Process.Start(startInfo);
startInfo.FileName = "batti2.bat";
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
Process.Start(startInfo);
*/
startInfo.FileName = "blat.exe";
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.Arguments = "-install " + smtp_server + " " + from_email;
Process.Start(startInfo);
startInfo.FileName = "blat.exe";
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.Arguments = mailcontent + " -to " + to_email + " -subject " + subject + " -attach " + attach_dir + filename;
var process = Process.Start(startInfo);
process.WaitForExit();
File.Delete(attach_dir + filename);
//}
}
else
{
var stopwatch = Stopwatch.StartNew();
stopwatch = Stopwatch.StartNew();
Thread.Sleep(1000);
stopwatch.Stop();
}
}
}
答案 0 :(得分:1)
你有一个无限循环。因此,就主机系统而言,您的应用程序永远不会响应。因此,它永远不会成功“启动”(OnStart
永不返回),主机终止明显破坏的过程。
这意味着您希望您的服务每秒都做一些事情:
Thread.Sleep(1000);
您可以使用Timer
对象完成此操作。您在OnStart
中真正需要做的就是初始化该对象:
this.timer = new System.Timers.Timer();
this.timer.Interval = 1000;
this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimerTick);
this.timer.Start();
然后有一个tick事件的处理程序:
public void OnTimerTick(object sender, System.Timers.ElapsedEventArgs args)
{
// perform your once-every-second logic here
}
这样可以更合适地使用系统而无需手动休眠线程并使用无限循环,正如您所看到的那样导致应用程序无限期地挂起。