Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cant write to a file using a thread

I'm writing a windows service (C#) that does a task repetitively. I'm using a thread to complete my requirement. Now I need to maintain a log file that keeps logs regarding the operation.

My service class is as follow

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;
    }


}

I have a separate class call "ProgramLog" to handle all the log related operations.This is that class.

 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
} 

According to the above class, When I start the service it needs to create folder call "Log" where it does not exists, then it creates a text file inside that folder and lastly it starts to create the log entries.

Even though the thread is working correctly it never touches the "ProgramLog" methods. I checked by directly calling the method "loopTrough". then its working fine.

Please help me to resolve this bug.

Thank you

like image 252
Sandaru Avatar asked Oct 31 '22 22:10

Sandaru


1 Answers

You declare a Thread workerThread = new Thread(loopTrough);, but you don't start this Thread. Just call workerThread.Start().

like image 193
Sattar Imamov Avatar answered Nov 13 '22 02:11

Sattar Imamov