无法使用线程写入文件

时间:2015-08-04 09:53:02

标签: c# multithreading service

我正在编写一个重复执行任务的Windows服务(C#)。我使用线程来完成我的要求。现在我需要维护一个日志文件来保存有关操作的日志。

我的服务类如下

public partial class CPEService : ServiceBase
{
    static ServiceBot bot = new ServiceBot();
    static ProgramLog logger = new ProgramLog();//ProgramLog Object

    private static bool state = true;

    //private static int count = 1;
    //private System.Timers.Timer timer;
    public CPEService()
    {
        InitializeComponent();
    }
            internal void TestStartupAndStop()
    {
        Thread workerThread = new Thread(loopTrough);
        workerThread.Start();
    }

    protected override void OnStart(string[] args)
    {
        Thread workerThread = new Thread(loopTrough);
        workerThread.Start(); 
    }

    private void loopTrough()
    {
        logger.log("Thread fired");
        while (state)
        {
            logger.log("Thread fired"); //This is not Working
            bot.start();
            Thread.Sleep(180000);
        }
    }

    protected override void OnStop()
    {
        state = false;
    }


}

我有一个单独的课程电话" ProgramLog"处理所有与日志相关的操作。这就是那个类。

 public class ProgramLog
{
    string fileName = "";//Global variable to store file name

    #region method to handle usual log records
    public void log(string text)//create normal Log text
    {
        fileName = "Log\\" + DateTime.Now.Date.ToString("d").Replace('/', '_') + ".txt";
        if (File.Exists(AppDomain.CurrentDomain.BaseDirectory+fileName))
        {
            using (FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + fileName, FileMode.Append))
            using (TextWriter tw = new StreamWriter(fs))
            {
                tw.WriteLine(text);
                tw.Flush();
                tw.Close();
                fs.Close();
            }
        }
        else
        {
            createFolder();
            log(text);
        }
    }
    #endregion

    #region log Error record 
    public void logError(string text, string className,int LineNumber, string Stacktrace)//create error text
    {
        fileName = "Log\\" + DateTime.Now.Date.ToString("d").Replace('/', '_') + ".txt";
        if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + fileName))
        {
            using (FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + fileName, FileMode.Append))
            using (TextWriter tw = new StreamWriter(fs))
            {
                tw.WriteLine("**************************ERROR****************************");
                tw.WriteLine(text);
                tw.WriteLine("In Class :{0}", className);
                tw.WriteLine("In Line :{0}", LineNumber);
                tw.WriteLine("ERROR :{0}",Stacktrace);
                tw.WriteLine("***********************************************************");
            }
        }
        else
        {
            createFolder();
            logError(text,className,LineNumber,Stacktrace);
        }
    }
    #endregion

    #region create folder to store log files
    public void createFolder()//create a folder for Log files
    {
        try
        {
            if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "Log"))
            {
                string folderName = "Log";
                Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + folderName);
                FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + fileName, FileMode.Create);
                StreamWriter sr = new StreamWriter(fs);
                sr.Flush();
                sr.Close();
                fs.Close();
            }
            else
            {
                FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + fileName, FileMode.Create);
                StreamWriter sr = new StreamWriter(fs);
                sr.Flush();
                sr.Close();
                fs.Close(); 
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.StackTrace);
        }
    }
    #endregion
} 

根据上面的类,当我启动服务时,它需要创建文件夹调用" Log"如果它不存在,那么它在该文件夹中创建一个文本文件,最后它开始创建日志条目。

即使线程正常工作,它也永远不会触及" ProgramLog"方法。我通过直接调用方法" loopTrough"来检查。然后它的工作正常。

请帮我解决这个错误。

谢谢

1 个答案:

答案 0 :(得分:2)

您声明了Thread workerThread = new Thread(loopTrough);,但未启动此Thread。只需致电workerThread.Start()