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 ;
}
{
// 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 ;
}
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
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();
}
}
{
/// <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();
}
}