AsyncLogFileWriter.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace Logging.Base
  7. {
  8. public class AsyncLogFileWriter
  9. {
  10. private readonly StreamWriter writer;
  11. public AsyncLogFileWriter(string path)
  12. {
  13. var fileInfo = new FileInfo(path);
  14. if (!fileInfo.Directory?.Exists ?? false) fileInfo.Directory?.Create();
  15. writer = new StreamWriter(path) {AutoFlush = true};
  16. }
  17. [Obsolete("Use WriteDataLine(values)")] //TODO
  18. public async Task WriteDataLine<T>(T xValue, IEnumerable<T> values)
  19. {
  20. await writer.WriteLineAsync($"{xValue}\t{string.Join("\t", values)}");
  21. }
  22. public async Task WriteDataLine<T>(IEnumerable<T> values)
  23. {
  24. await writer.WriteLineAsync($"{string.Join("\t", values)}");
  25. }
  26. public async Task WriteDataLines<T>(IEnumerable<IEnumerable<T>> lines)
  27. {
  28. //This method is ultimately called by an Update Method. Unity doesn't await Update
  29. var sb = new StringBuilder();
  30. foreach (var l in lines) sb.Append($"{string.Join("\t", l)}\n");
  31. await writer.WriteAsync(sb.ToString());
  32. }
  33. public void Dispose()
  34. {
  35. writer?.Close();
  36. }
  37. }
  38. }