Pra*_*uja 18 c# windows windows-services sql-server-2005
我想创建一个将访问我的数据库的Windows服务.我的数据库是SQL Server 2005.
其实我在网站上工作,我的数据库在我们的服务器内.我需要每秒访问我的数据库并更新记录.为此,我需要制作一个将安装到我们的服务器并执行任务的Windows服务.
我一直在从我的本地机器访问数据库,然后运行该服务,但问题是我不知道如何测试这项服务.
我试着安装到我的本地机器上.它安装然后我运行服务但它没有执行任务,我认为服务无法连接数据库.
服务及其安装程序没有问题.唯一的问题是如何测试我的Windows服务.
mar*_*c_s 20
您始终可以创建服务/控制台应用程序混合,并使用控制台应用程序进行测试.
您需要做的是这样的事情 - 在您program.cs的Main方法中,将方法更改为运行服务,或者可选地作为控制台应用程序运行:
static class Program
{
static void Main(params string[] args)
{
string firstArgument = string.Empty;
if (args.Length > 0)
{
firstArgument = args[0].ToLowerInvariant();
}
if (string.Compare(firstArgument, "-console", true) == 0)
{
new YourServiceClass().RunConsole(args);
}
else
{
ServiceBase[] ServicesToRun = new ServiceBase[] { new YourServiceClass() };
ServiceBase.Run(ServicesToRun);
}
}
Run Code Online (Sandbox Code Playgroud)
然后在你的服务类上,它继承ServiceBase并拥有OnStart和OnStop,添加RunConsole方法如下:
public void RunConsole(string[] args)
{
OnStart(args);
Console.WriteLine("Service running ... press <ENTER> to stop");
//Console.ReadLine();
while (true)
{ }
OnStop();
}
Run Code Online (Sandbox Code Playgroud)
现在,如果要运行应用程序来测试其功能,只需使用-console命令行参数启动EXE ,并在RunConsole方法中放置断点.