public class Worker
{
// This method will be called when the thread is started.
public void DoWork()
{
Console.WriteLine("主線程成功啟動!");
while (!_shouldStop)
{
Console.WriteLine( DateTime.Now.ToString("yyyyMMddHHmmss")+":主進程正在工作!" );
guard.guardId = true;
GetNewEmails();
System.Threading.Thread.Sleep(1000 * refreshinterval);
}
Console.WriteLine("主線程關閉!");
}
public void RequestStop()
{
_shouldStop = true;
}
public void RequestOpen()
{
_shouldStop = false;
}
public bool shouldStop
{
get { return _shouldStop; }
set { _shouldStop = value; }
}
private bool _shouldStop = false;
}
guard.cs
class guard
{
static public bool guardId = false;
static public int guardinterval = Convert.ToInt32(ConfigurationManager.AppSettings["guardinterval"]);
static public void guardThread()
{
while (true)
{
System.Threading.Thread.Sleep(1000 * guardinterval);
if (!guardId)
{
Console.WriteLine("主線程異常!");
try
{
// Program.workerThread.Abort();
Program.workerObject.RequestStop();
Program.workerThread.Join();
Thread.Sleep(6000);
Program.workerThread = null;
Console.WriteLine("主線程賦值為空白!");
Program.workerThread = new Thread(Program.workerObject.DoWork);
Console.WriteLine("主線程重新建立!");
Program.workerThread.Start();
Program.workerObject.RequestOpen();
}
catch (Exception e)
{
Console.WriteLine("守護進程:" + e.Message);
}
}
else
{
Console.WriteLine("主線程正常!");
}
guardId = false;
}
}
}
static class Program
{
/// <summary>
/// 應用程式的主進入點。
/// </summary>
static public Worker workerObject = new Worker();
static public guard guardobject = new guard();
static public Thread workerThread = null;
static public Thread guardThread=null;
static void Main()
{
workerThread = new Thread(workerObject.DoWork);
guardThread = new Thread(guard.guardThread);
workerThread.Start();
guardThread.Start();
}
}