public partial class testService : ServiceBase
{
private Thread workThread;
private DateTime lastUpdateTime = DateTime.Now.AddDays(-1);
private ThreadStatus Running = ThreadStatus.None;
public testService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
workThread = new Thread(new ThreadStart(this.do));
workThread.Start();
SysLog.WriteTrace("HHTravel.SCM.Exchange.ETLPkgService已启动");
while (!workThread.IsAlive) ;
}
protected override void OnStop()
{
Running = ThreadStatus.Stopping;
for (int i = 0; i < 10; i++)
{
Thread.Sleep(2000);
if (Running == ThreadStatus.Stoped)
break;
}
SysLog.WriteTrace("HHTravel.SCM.Exchange.ETLPkgService已停止");
}
private void do()
{
Running = ThreadStatus.Running;
int intervalMinuts = int.Parse(ConfigurationManager.AppSettings["ETLIntervalMinuts"]);
while (Running == ThreadStatus.Running)
{
TimeSpan ts = DateTime.Now - lastUpdateTime;
if (ts.TotalMinutes >= intervalMinuts)
{
try
{
Execute exe = new Execute();
exe.Process();
}
catch (Exception e)
{
SysLog.WriteException("HHTravel.SCM.Exchange.ETLPkgService", e);
}
lastUpdateTime = DateTime.Now;
}
Thread.Sleep(1000);
}
Running = ThreadStatus.Stoped;
}
//线程三态,线程五态、七态,少了一个wailt(sleep、blocked),不过这里不控制
//如同订单状态的变迁一样,在一定条件下可以转换
private enum ThreadStatus
{
None,
Running,
Stopping,
Stoped
}
====================================
using System;
using System.Threading;
class Test
{
public static void Main()
{
Thread newThread = new Thread(new ThreadStart(TestMethod));
Console.WriteLine(newThread.ThreadState.ToString());
newThread.Start();
Console.WriteLine(newThread.ThreadState.ToString());
Thread.Sleep(1000);
// Abort newThread.
Console.WriteLine("Main aborting new thread.");
stop = true;
// newThread.Abort("Information from Main.");
Console.WriteLine(newThread.ThreadState.ToString());
// Wait for the thread to terminate.
newThread.Join();
Console.WriteLine(newThread.ThreadState.ToString());
Console.WriteLine("New thread terminated - Main exiting.");
Console.ReadLine();
}
static void TestMethod()
{
try
{
while(true)
{
Console.WriteLine("New thread running.");
Thread.Sleep(1000);
}
}
catch(ThreadAbortException abortException)
{
Console.WriteLine((string)abortException.ExceptionState);
}
}
}