DeferredFormatter.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. using System;
  2. using System.Collections;
  3. using System.IO;
  4. namespace SmartCoalApplication
  5. {
  6. public sealed class DeferredFormatter
  7. {
  8. private ArrayList objects = ArrayList.Synchronized(new ArrayList());
  9. private bool used = false;
  10. private object context;
  11. private long totalSize;
  12. private long totalReportedBytes;
  13. private bool useCompression;
  14. private object lockObject = new object();
  15. public object Context
  16. {
  17. get
  18. {
  19. return this.context;
  20. }
  21. }
  22. public bool UseCompression
  23. {
  24. get
  25. {
  26. return this.useCompression;
  27. }
  28. }
  29. public DeferredFormatter()
  30. : this(false, null)
  31. {
  32. }
  33. public DeferredFormatter(bool useCompression, object context)
  34. {
  35. this.useCompression = useCompression;
  36. this.context = context;
  37. }
  38. public void AddDeferredObject(IDeferredSerializable theObject, long objectByteSize)
  39. {
  40. if (used)
  41. {
  42. throw new InvalidOperationException("object already finished serialization");
  43. }
  44. this.totalSize += objectByteSize;
  45. objects.Add(theObject);
  46. }
  47. public event EventHandler ReportedBytesChanged;
  48. private void OnReportedBytesChanged()
  49. {
  50. if (ReportedBytesChanged != null)
  51. {
  52. ReportedBytesChanged(this, EventArgs.Empty);
  53. }
  54. }
  55. public long ReportedBytes
  56. {
  57. get
  58. {
  59. lock (lockObject)
  60. {
  61. return totalReportedBytes;
  62. }
  63. }
  64. }
  65. /// <summary>
  66. /// Reports that bytes have been successfully been written.
  67. /// </summary>
  68. /// <param name="bytes"></param>
  69. public void ReportBytes(long bytes)
  70. {
  71. lock (lockObject)
  72. {
  73. totalReportedBytes += bytes;
  74. }
  75. OnReportedBytesChanged();
  76. }
  77. public void FinishSerialization(Stream output)
  78. {
  79. if (used)
  80. {
  81. throw new InvalidOperationException("object already finished deserialization or serialization");
  82. }
  83. used = true;
  84. foreach (IDeferredSerializable obj in this.objects)
  85. {
  86. obj.FinishSerialization(output, this);
  87. }
  88. this.objects = null;
  89. }
  90. public void FinishDeserialization(Stream input)
  91. {
  92. if (used)
  93. {
  94. throw new InvalidOperationException("object already finished deserialization or serialization");
  95. }
  96. used = true;
  97. foreach (IDeferredSerializable obj in this.objects)
  98. {
  99. obj.FinishDeserialization(input, this);
  100. }
  101. this.objects = null;
  102. }
  103. }
  104. }