cha*_*r m 5 c# windows-services
我的问题是,这是最好的做法.找不到任何好的例子.我在VS2005创建的文件中有以下代码:
public partial class ObjectFolder : ServiceBase
{
protected override void OnStart(string[] args)
{
ObjectFolderApp.Initialize();
ObjectFolderApp.StartMonitorAndWork();
}
protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop yourservice.
}
}
Run Code Online (Sandbox Code Playgroud)
然后:
class ObjectFolderApp
{
public static bool Initialize()
{
//all init stuff
return true;
}
public static void StartMonitorAndWork()
{
Thread worker = new Thread(MonitorAndWork);
worker.Start();
}
private static void MonitorAndWork()
{
int loopTime = 60000;
if (int.TryParse(_cfgValues.GetConfigValue("OfWaitLoop"), out loopTime))
loopTime = 1000 * loopTime;
while (true)
{
/* create+open connection and fill DataSet */
DataSet ofDataSet = new DataSet("ObjectFolderSet");
using (_cnctn = _dbFactory.CreateConnection())
{
_cnctn.Open();
//do all kinds of database stuff
}
Thread.Sleep(loopTime);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Aar*_*ght 14
从这个问题重新解析我的答案,推荐的方法是使用计时器和以下代码:
public class MyService : ServiceBase
{
private Timer workTimer; // System.Threading.Timer
protected override void OnStart(string[] args)
{
workTimer = new Timer(new TimerCallback(DoWork), null, 5000, 5000);
base.OnStart(args);
}
protected override void OnStop()
{
workTimer.Dispose();
base.OnStop();
}
private void DoWork(object state)
{
RunScheduledTasks(); // Do some work
}
}
Run Code Online (Sandbox Code Playgroud)
简单!
请注意,Timer正在使用的类型System.Threading.Timer与Justin指定的相同.
| 归档时间: |
|
| 查看次数: |
7629 次 |
| 最近记录: |