C# windows服务中使用线程的问题
先贴出代码示例:
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
Process.Start();
}
protected override void OnStop()
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\\log.txt", true))
{
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Service:Stop.");
}
}
public static class Process
{
public static void Start()
{
ThreadStart start = new ThreadStart(ThreadAction);
Thread th = new Thread(start);
th.IsBackground = true;
th.Start();
}
public static void ThreadAction()
{
while (true)
{
try
{
//do something
}
catch (Exception ex)
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\\log.txt", true))
{
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Service:Start.错误" + ex.ToString());
}
}
}
}
}
}
问题是:当我在try中执行代码的时候,如果出现错误:比如“远程服务器返回错误: (500) 内部服务器错误。”或者“操作超时”,,他就会不停的记录日志,每秒钟都记录很多很多!!!导致日志文件没几天就变得很大!!!!!!求前辈们指教!!!这个问题怎么解决?????