using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleAdvancedTopics { public class Customers : IDisposable { private bool disposed = false; // ## change to static to handle mutiple Customers ### private static StreamWriter logfile; // "customer_log.txt" // ### Add Lock For Multiple Customers ### private static readonly object logLock = new object(); static Customers() { logfile = new StreamWriter("customer_log.txt", true); } private void LogMessage(string message) { lock (logLock) { logfile.WriteLine(message); logfile.Flush(); } } // ### EOAdd ### public int Id { get; set; } public string Name { get; set; } // constructor public Customers(int id, string name) { Id = id; Name = name; // ### Add to support multiple writelines from cusomters LogMessage($"Customer {Id} created."); /* // Streamwriter to a log file for single customer // Block Comment logfile = new StreamWriter("customer_log.txt", true); logfile.WriteLine($"Customer {Id} added to stream."); logfile.Flush(); // first option to clear the buffer // */ } // constructor public void SaveOrder(string orderDetails) { if (disposed) // throws when True throw new ObjectDisposedException("Customers"); /* Single instance logfile.WriteLine($"Order saved for customer {Id} {Name}"); logfile.Flush(); */ // Multiple Instances LogMessage($"Order saved for customer {Id}."); } // SaveOrder public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } // Dispose protected virtual void Dispose(bool disposing) { if (!disposing) { // Not True if (disposing) { // True // Dispose of managed resources // logfile is null ok // logfile is !null Dispose /* Single Instance if (logfile != null) { logfile.WriteLine($"Customer {Id} resource manually disposed of."); logfile.Flush(); logfile.Dispose(); } // if logfile */ // ### Multiple Instances LogMessage($"Customer {Id} disposed"); } // if disposed // if !disposed // free unmanaged resource disposed = true; } // if !disposed } // Dispose(bool) // Finalizer destructor ~Customers() { Dispose(false); } // Finalizer } // Customers Class } // namespace