1
0

AsyncLogFileWriter.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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)
  15. {
  16. fileInfo.Directory?.Create();
  17. }
  18. writer = new StreamWriter(path) {AutoFlush = true};
  19. }
  20. [Obsolete("Use WriteDataLine(values)")] //TODO
  21. public async Task WriteDataLine<T>(T xValue, IEnumerable<T> values)
  22. {
  23. await writer.WriteLineAsync($"{xValue}\t{string.Join("\t", values)}");
  24. }
  25. public async Task WriteDataLine<T>(IEnumerable<T> values)
  26. {
  27. await writer.WriteLineAsync($"{string.Join("\t", values)}");
  28. }
  29. public async Task WriteDataLines<T>(IEnumerable<IEnumerable<T>> lines)
  30. {
  31. //This method is ultimately called by an Update Method. Unity doesn't await Update
  32. var sb = new StringBuilder();
  33. foreach (var l in lines)
  34. {
  35. sb.Append($"{string.Join("\t", l)}\n");
  36. }
  37. await writer.WriteAsync(sb.ToString());
  38. }
  39. public void Dispose()
  40. {
  41. writer?.Close();
  42. }
  43. }
  44. }