Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to prevent a method of a class to be called before the class is ready?
    primarykey
    data
    text
    <p>Still exploring C# ... so bare with me please.</p> <p>Here is my custom "logger" class, which helps me create logs file in my project.</p> <pre><code>namespace MyProject { class Logger { private FileInfo fFile; private DirectoryInfo dDir; /// &lt;summary&gt;Add a new entry to the log file.&lt;/summary&gt; /// &lt;param name="sData"&gt;The line to add.&lt;/param&gt; public void Add(string sData) { DateTime CurrTime = DateTime.Now; if (fFile.Length &gt; 1048576) { fFile.MoveTo(Path.Combine(dDir.FullName, CurrTime.ToShortDateString() + fFile.Name)); fFile = new FileInfo(Path.Combine(dDir.FullName,fFile.Name)); using (StreamWriter sw = fFile.CreateText()) { sw.WriteLine("{0:u}|{1}", CurrTime, sData); } } else { using (StreamWriter sw = fFile.AppendText()) { sw.WriteLine("{0:u}|{1}", CurrTime, sData); } } } /// &lt;summary&gt;Logger instance&lt;/summary&gt; /// &lt;param name="sFile"&gt;Full name of the file to use as logs. Ex : "MyLogs.txt"&lt;/param&gt; public Logger(string sFile) { dDir = new DirectoryInfo(Path.Combine(MyProject.AppPath, "logs")); if (!dDir.Exists) { dDir.Create(); } fFile = new FileInfo(Path.Combine(dDir.FullName,sFile)); if (!fFile.Exists) { using (StreamWriter sw = fFile.CreateText()) { sw.WriteLine("{0:u}|Logger Started", DateTime.Now); } } else { Add("Logger Started"); } } } } </code></pre> <p>The problem I have with this code is, apparently, sometimes, Logger.Add is called before the new instance of that logger had time to create the file. So my program crashes saying "file not found", although, the file ends up being created in the end, and if I restart my program using the same filename for the logs, everything works fine (because the file exists now ...)</p> <p>Instead of just making sure logger.add is not called before the file is created, is there a way to "lock" the class ?</p> <p>I've tried the lock method but it didn't work ... Lock(this) didn't do anything, and I can't use it on the method itself.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload