1.main函数:
class Program
{
static void Main(string[] args)
{
log4net.Config.XmlConfigurator.Configure();
ConsoleOutput.ConsoleEnabled = true;
ConsoleRun();
}
private static void ConsoleRun()
{
string title = ConfigurationManager.AppSettings["ProgramTitle"];
Console.Title = title;
Console.WriteLine(title);
Console.WriteLine();
ConsoleOutput.ShowInfomationLine(title + "程序开始");
var backgroudWorker = new BackgroundWorker { WorkerSupportsCancellation = true };
backgroudWorker.DoWork += (sender, e) =>
{
var backgroundWorker = (BackgroundWorker)sender;
NoticeWorker.Deamon(backgroundWorker);
};
backgroudWorker.RunWorkerAsync();
Console.ReadLine();
Console.Title = title + "消息队列 -- 正在停止 ... ";
backgroudWorker.CancelAsync();
Console.WriteLine(@"
****************************************
* *
* 服务已停止。请按回车键关闭此窗口。 *
* *
****************************************
");
Console.Title = title + "消息队列 -- 已停止";
Console.ReadLine();
}
}
2.NoticeWorker类
public class NoticeWorker
{
public static void Deamon(BackgroundWorker backgroundWorker)
{
while (!backgroundWorker.CancellationPending)
{
try
{
//do job
}
catch (Exception ex)
{
_logger.Error("程序出错", ex);
}
}
}
}