TextWriter.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Text;
  5. using System.Threading;
  6. using System.Globalization;
  7. using System.Threading.Tasks;
  8. using System.Runtime.CompilerServices;
  9. using System.Runtime.InteropServices;
  10. using System.Buffers;
  11. namespace System.IO
  12. {
  13. // This abstract base class represents a writer that can write a sequential
  14. // stream of characters. A subclass must minimally implement the
  15. // Write(char) method.
  16. //
  17. // This class is intended for character output, not bytes.
  18. // There are methods on the Stream class for writing bytes.
  19. public abstract partial class TextWriter : MarshalByRefObject, IDisposable, IAsyncDisposable
  20. {
  21. public static readonly TextWriter Null = new NullTextWriter();
  22. // We don't want to allocate on every TextWriter creation, so cache the char array.
  23. private static readonly char[] s_coreNewLine = Environment.NewLine.ToCharArray();
  24. /// <summary>
  25. /// This is the 'NewLine' property expressed as a char[].
  26. /// It is exposed to subclasses as a protected field for read-only
  27. /// purposes. You should only modify it by using the 'NewLine' property.
  28. /// In particular you should never modify the elements of the array
  29. /// as they are shared among many instances of TextWriter.
  30. /// </summary>
  31. protected char[] CoreNewLine = s_coreNewLine;
  32. private string CoreNewLineStr = Environment.NewLine;
  33. // Can be null - if so, ask for the Thread's CurrentCulture every time.
  34. private IFormatProvider _internalFormatProvider;
  35. protected TextWriter()
  36. {
  37. _internalFormatProvider = null; // Ask for CurrentCulture all the time.
  38. }
  39. protected TextWriter(IFormatProvider formatProvider)
  40. {
  41. _internalFormatProvider = formatProvider;
  42. }
  43. public virtual IFormatProvider FormatProvider
  44. {
  45. get
  46. {
  47. if (_internalFormatProvider == null)
  48. {
  49. return CultureInfo.CurrentCulture;
  50. }
  51. else
  52. {
  53. return _internalFormatProvider;
  54. }
  55. }
  56. }
  57. public virtual void Close()
  58. {
  59. Dispose(true);
  60. GC.SuppressFinalize(this);
  61. }
  62. protected virtual void Dispose(bool disposing)
  63. {
  64. }
  65. public void Dispose()
  66. {
  67. Dispose(true);
  68. GC.SuppressFinalize(this);
  69. }
  70. public virtual ValueTask DisposeAsync()
  71. {
  72. try
  73. {
  74. Dispose();
  75. return default;
  76. }
  77. catch (Exception exc)
  78. {
  79. return new ValueTask(Task.FromException(exc));
  80. }
  81. }
  82. // Clears all buffers for this TextWriter and causes any buffered data to be
  83. // written to the underlying device. This default method is empty, but
  84. // descendant classes can override the method to provide the appropriate
  85. // functionality.
  86. public virtual void Flush()
  87. {
  88. }
  89. public abstract Encoding Encoding
  90. {
  91. get;
  92. }
  93. /// <summary>
  94. /// Returns the line terminator string used by this TextWriter. The default line
  95. /// terminator string is Environment.NewLine, which is platform specific.
  96. /// On Windows this is a carriage return followed by a line feed ("\r\n").
  97. /// On OSX and Linux this is a line feed ("\n").
  98. /// </summary>
  99. /// <remarks>
  100. /// The line terminator string is written to the text stream whenever one of the
  101. /// WriteLine methods are called. In order for text written by
  102. /// the TextWriter to be readable by a TextReader, only one of the following line
  103. /// terminator strings should be used: "\r", "\n", or "\r\n".
  104. /// </remarks>
  105. public virtual string NewLine
  106. {
  107. get { return CoreNewLineStr; }
  108. set
  109. {
  110. if (value == null)
  111. {
  112. value = Environment.NewLine;
  113. }
  114. CoreNewLineStr = value;
  115. CoreNewLine = value.ToCharArray();
  116. }
  117. }
  118. // Writes a character to the text stream. This default method is empty,
  119. // but descendant classes can override the method to provide the
  120. // appropriate functionality.
  121. //
  122. public virtual void Write(char value)
  123. {
  124. }
  125. // Writes a character array to the text stream. This default method calls
  126. // Write(char) for each of the characters in the character array.
  127. // If the character array is null, nothing is written.
  128. //
  129. public virtual void Write(char[] buffer)
  130. {
  131. if (buffer != null)
  132. {
  133. Write(buffer, 0, buffer.Length);
  134. }
  135. }
  136. // Writes a range of a character array to the text stream. This method will
  137. // write count characters of data into this TextWriter from the
  138. // buffer character array starting at position index.
  139. //
  140. public virtual void Write(char[] buffer, int index, int count)
  141. {
  142. if (buffer == null)
  143. {
  144. throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
  145. }
  146. if (index < 0)
  147. {
  148. throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
  149. }
  150. if (count < 0)
  151. {
  152. throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
  153. }
  154. if (buffer.Length - index < count)
  155. {
  156. throw new ArgumentException(SR.Argument_InvalidOffLen);
  157. }
  158. for (int i = 0; i < count; i++) Write(buffer[index + i]);
  159. }
  160. // Writes a span of characters to the text stream.
  161. //
  162. public virtual void Write(ReadOnlySpan<char> buffer)
  163. {
  164. char[] array = ArrayPool<char>.Shared.Rent(buffer.Length);
  165. try
  166. {
  167. buffer.CopyTo(new Span<char>(array));
  168. Write(array, 0, buffer.Length);
  169. }
  170. finally
  171. {
  172. ArrayPool<char>.Shared.Return(array);
  173. }
  174. }
  175. // Writes the text representation of a boolean to the text stream. This
  176. // method outputs either bool.TrueString or bool.FalseString.
  177. //
  178. public virtual void Write(bool value)
  179. {
  180. Write(value ? "True" : "False");
  181. }
  182. // Writes the text representation of an integer to the text stream. The
  183. // text representation of the given value is produced by calling the
  184. // int.ToString() method.
  185. //
  186. public virtual void Write(int value)
  187. {
  188. Write(value.ToString(FormatProvider));
  189. }
  190. // Writes the text representation of an integer to the text stream. The
  191. // text representation of the given value is produced by calling the
  192. // uint.ToString() method.
  193. //
  194. [CLSCompliant(false)]
  195. public virtual void Write(uint value)
  196. {
  197. Write(value.ToString(FormatProvider));
  198. }
  199. // Writes the text representation of a long to the text stream. The
  200. // text representation of the given value is produced by calling the
  201. // long.ToString() method.
  202. //
  203. public virtual void Write(long value)
  204. {
  205. Write(value.ToString(FormatProvider));
  206. }
  207. // Writes the text representation of an unsigned long to the text
  208. // stream. The text representation of the given value is produced
  209. // by calling the ulong.ToString() method.
  210. //
  211. [CLSCompliant(false)]
  212. public virtual void Write(ulong value)
  213. {
  214. Write(value.ToString(FormatProvider));
  215. }
  216. // Writes the text representation of a float to the text stream. The
  217. // text representation of the given value is produced by calling the
  218. // float.ToString(float) method.
  219. //
  220. public virtual void Write(float value)
  221. {
  222. Write(value.ToString(FormatProvider));
  223. }
  224. // Writes the text representation of a double to the text stream. The
  225. // text representation of the given value is produced by calling the
  226. // double.ToString(double) method.
  227. //
  228. public virtual void Write(double value)
  229. {
  230. Write(value.ToString(FormatProvider));
  231. }
  232. public virtual void Write(decimal value)
  233. {
  234. Write(value.ToString(FormatProvider));
  235. }
  236. // Writes a string to the text stream. If the given string is null, nothing
  237. // is written to the text stream.
  238. //
  239. public virtual void Write(string value)
  240. {
  241. if (value != null)
  242. {
  243. Write(value.ToCharArray());
  244. }
  245. }
  246. // Writes the text representation of an object to the text stream. If the
  247. // given object is null, nothing is written to the text stream.
  248. // Otherwise, the object's ToString method is called to produce the
  249. // string representation, and the resulting string is then written to the
  250. // output stream.
  251. //
  252. public virtual void Write(object value)
  253. {
  254. if (value != null)
  255. {
  256. if (value is IFormattable f)
  257. {
  258. Write(f.ToString(null, FormatProvider));
  259. }
  260. else
  261. Write(value.ToString());
  262. }
  263. }
  264. /// <summary>
  265. /// Equivalent to Write(stringBuilder.ToString()) however it uses the
  266. /// StringBuilder.GetChunks() method to avoid creating the intermediate string
  267. /// </summary>
  268. /// <param name="value">The string (as a StringBuilder) to write to the stream</param>
  269. public virtual void Write(StringBuilder value)
  270. {
  271. if (value != null)
  272. {
  273. foreach (ReadOnlyMemory<char> chunk in value.GetChunks())
  274. Write(chunk);
  275. }
  276. }
  277. // Writes out a formatted string. Uses the same semantics as
  278. // string.Format.
  279. //
  280. public virtual void Write(string format, object arg0)
  281. {
  282. Write(string.Format(FormatProvider, format, arg0));
  283. }
  284. // Writes out a formatted string. Uses the same semantics as
  285. // string.Format.
  286. //
  287. public virtual void Write(string format, object arg0, object arg1)
  288. {
  289. Write(string.Format(FormatProvider, format, arg0, arg1));
  290. }
  291. // Writes out a formatted string. Uses the same semantics as
  292. // string.Format.
  293. //
  294. public virtual void Write(string format, object arg0, object arg1, object arg2)
  295. {
  296. Write(string.Format(FormatProvider, format, arg0, arg1, arg2));
  297. }
  298. // Writes out a formatted string. Uses the same semantics as
  299. // string.Format.
  300. //
  301. public virtual void Write(string format, params object[] arg)
  302. {
  303. Write(string.Format(FormatProvider, format, arg));
  304. }
  305. // Writes a line terminator to the text stream. The default line terminator
  306. // is Environment.NewLine, but this value can be changed by setting the NewLine property.
  307. //
  308. public virtual void WriteLine()
  309. {
  310. Write(CoreNewLine);
  311. }
  312. // Writes a character followed by a line terminator to the text stream.
  313. //
  314. public virtual void WriteLine(char value)
  315. {
  316. Write(value);
  317. WriteLine();
  318. }
  319. // Writes an array of characters followed by a line terminator to the text
  320. // stream.
  321. //
  322. public virtual void WriteLine(char[] buffer)
  323. {
  324. Write(buffer);
  325. WriteLine();
  326. }
  327. // Writes a range of a character array followed by a line terminator to the
  328. // text stream.
  329. //
  330. public virtual void WriteLine(char[] buffer, int index, int count)
  331. {
  332. Write(buffer, index, count);
  333. WriteLine();
  334. }
  335. public virtual void WriteLine(ReadOnlySpan<char> buffer)
  336. {
  337. char[] array = ArrayPool<char>.Shared.Rent(buffer.Length);
  338. try
  339. {
  340. buffer.CopyTo(new Span<char>(array));
  341. WriteLine(array, 0, buffer.Length);
  342. }
  343. finally
  344. {
  345. ArrayPool<char>.Shared.Return(array);
  346. }
  347. }
  348. // Writes the text representation of a boolean followed by a line
  349. // terminator to the text stream.
  350. //
  351. public virtual void WriteLine(bool value)
  352. {
  353. Write(value);
  354. WriteLine();
  355. }
  356. // Writes the text representation of an integer followed by a line
  357. // terminator to the text stream.
  358. //
  359. public virtual void WriteLine(int value)
  360. {
  361. Write(value);
  362. WriteLine();
  363. }
  364. // Writes the text representation of an unsigned integer followed by
  365. // a line terminator to the text stream.
  366. //
  367. [CLSCompliant(false)]
  368. public virtual void WriteLine(uint value)
  369. {
  370. Write(value);
  371. WriteLine();
  372. }
  373. // Writes the text representation of a long followed by a line terminator
  374. // to the text stream.
  375. //
  376. public virtual void WriteLine(long value)
  377. {
  378. Write(value);
  379. WriteLine();
  380. }
  381. // Writes the text representation of an unsigned long followed by
  382. // a line terminator to the text stream.
  383. //
  384. [CLSCompliant(false)]
  385. public virtual void WriteLine(ulong value)
  386. {
  387. Write(value);
  388. WriteLine();
  389. }
  390. // Writes the text representation of a float followed by a line terminator
  391. // to the text stream.
  392. //
  393. public virtual void WriteLine(float value)
  394. {
  395. Write(value);
  396. WriteLine();
  397. }
  398. // Writes the text representation of a double followed by a line terminator
  399. // to the text stream.
  400. //
  401. public virtual void WriteLine(double value)
  402. {
  403. Write(value);
  404. WriteLine();
  405. }
  406. public virtual void WriteLine(decimal value)
  407. {
  408. Write(value);
  409. WriteLine();
  410. }
  411. // Writes a string followed by a line terminator to the text stream.
  412. //
  413. public virtual void WriteLine(string value)
  414. {
  415. if (value != null)
  416. {
  417. Write(value);
  418. }
  419. Write(CoreNewLineStr);
  420. }
  421. /// <summary>
  422. /// Equivalent to WriteLine(stringBuilder.ToString()) however it uses the
  423. /// StringBuilder.GetChunks() method to avoid creating the intermediate string
  424. /// </summary>
  425. public virtual void WriteLine(StringBuilder value)
  426. {
  427. Write(value);
  428. WriteLine();
  429. }
  430. // Writes the text representation of an object followed by a line
  431. // terminator to the text stream.
  432. //
  433. public virtual void WriteLine(object value)
  434. {
  435. if (value == null)
  436. {
  437. WriteLine();
  438. }
  439. else
  440. {
  441. // Call WriteLine(value.ToString), not Write(Object), WriteLine().
  442. // This makes calls to WriteLine(Object) atomic.
  443. if (value is IFormattable f)
  444. {
  445. WriteLine(f.ToString(null, FormatProvider));
  446. }
  447. else
  448. {
  449. WriteLine(value.ToString());
  450. }
  451. }
  452. }
  453. // Writes out a formatted string and a new line. Uses the same
  454. // semantics as string.Format.
  455. //
  456. public virtual void WriteLine(string format, object arg0)
  457. {
  458. WriteLine(string.Format(FormatProvider, format, arg0));
  459. }
  460. // Writes out a formatted string and a new line. Uses the same
  461. // semantics as string.Format.
  462. //
  463. public virtual void WriteLine(string format, object arg0, object arg1)
  464. {
  465. WriteLine(string.Format(FormatProvider, format, arg0, arg1));
  466. }
  467. // Writes out a formatted string and a new line. Uses the same
  468. // semantics as string.Format.
  469. //
  470. public virtual void WriteLine(string format, object arg0, object arg1, object arg2)
  471. {
  472. WriteLine(string.Format(FormatProvider, format, arg0, arg1, arg2));
  473. }
  474. // Writes out a formatted string and a new line. Uses the same
  475. // semantics as string.Format.
  476. //
  477. public virtual void WriteLine(string format, params object[] arg)
  478. {
  479. WriteLine(string.Format(FormatProvider, format, arg));
  480. }
  481. #region Task based Async APIs
  482. public virtual Task WriteAsync(char value)
  483. {
  484. var tuple = new Tuple<TextWriter, char>(this, value);
  485. return Task.Factory.StartNew(state =>
  486. {
  487. var t = (Tuple<TextWriter, char>)state;
  488. t.Item1.Write(t.Item2);
  489. },
  490. tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  491. }
  492. public virtual Task WriteAsync(string value)
  493. {
  494. var tuple = new Tuple<TextWriter, string>(this, value);
  495. return Task.Factory.StartNew(state =>
  496. {
  497. var t = (Tuple<TextWriter, string>)state;
  498. t.Item1.Write(t.Item2);
  499. },
  500. tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  501. }
  502. /// <summary>
  503. /// Equivalent to WriteAsync(stringBuilder.ToString()) however it uses the
  504. /// StringBuilder.GetChunks() method to avoid creating the intermediate string
  505. /// </summary>
  506. /// <param name="value">The string (as a StringBuilder) to write to the stream</param>
  507. public virtual Task WriteAsync(StringBuilder value, CancellationToken cancellationToken = default)
  508. {
  509. return
  510. cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) :
  511. value == null ? Task.CompletedTask :
  512. WriteAsyncCore(value, cancellationToken);
  513. async Task WriteAsyncCore(StringBuilder sb, CancellationToken ct)
  514. {
  515. foreach (ReadOnlyMemory<char> chunk in sb.GetChunks())
  516. {
  517. await WriteAsync(chunk, ct).ConfigureAwait(false);
  518. }
  519. }
  520. }
  521. public Task WriteAsync(char[] buffer)
  522. {
  523. if (buffer == null)
  524. {
  525. return Task.CompletedTask;
  526. }
  527. return WriteAsync(buffer, 0, buffer.Length);
  528. }
  529. public virtual Task WriteAsync(char[] buffer, int index, int count)
  530. {
  531. var tuple = new Tuple<TextWriter, char[], int, int>(this, buffer, index, count);
  532. return Task.Factory.StartNew(state =>
  533. {
  534. var t = (Tuple<TextWriter, char[], int, int>)state;
  535. t.Item1.Write(t.Item2, t.Item3, t.Item4);
  536. },
  537. tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  538. }
  539. public virtual Task WriteAsync(ReadOnlyMemory<char> buffer, CancellationToken cancellationToken = default) =>
  540. cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) :
  541. MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ?
  542. WriteAsync(array.Array, array.Offset, array.Count) :
  543. Task.Factory.StartNew(state =>
  544. {
  545. var t = (Tuple<TextWriter, ReadOnlyMemory<char>>)state;
  546. t.Item1.Write(t.Item2.Span);
  547. }, Tuple.Create(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  548. public virtual Task WriteLineAsync(char value)
  549. {
  550. var tuple = new Tuple<TextWriter, char>(this, value);
  551. return Task.Factory.StartNew(state =>
  552. {
  553. var t = (Tuple<TextWriter, char>)state;
  554. t.Item1.WriteLine(t.Item2);
  555. },
  556. tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  557. }
  558. public virtual Task WriteLineAsync(string value)
  559. {
  560. var tuple = new Tuple<TextWriter, string>(this, value);
  561. return Task.Factory.StartNew(state =>
  562. {
  563. var t = (Tuple<TextWriter, string>)state;
  564. t.Item1.WriteLine(t.Item2);
  565. },
  566. tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  567. }
  568. /// <summary>
  569. /// Equivalent to WriteLineAsync(stringBuilder.ToString()) however it uses the
  570. /// StringBuilder.GetChunks() method to avoid creating the intermediate string
  571. /// </summary>
  572. /// <param name="value">The string (as a StringBuilder) to write to the stream</param>
  573. public virtual Task WriteLineAsync(StringBuilder value, CancellationToken cancellationToken = default)
  574. {
  575. return
  576. cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) :
  577. value == null ? WriteAsync(CoreNewLine, cancellationToken) :
  578. WriteLineAsyncCore(value, cancellationToken);
  579. async Task WriteLineAsyncCore(StringBuilder sb, CancellationToken ct)
  580. {
  581. foreach (ReadOnlyMemory<char> chunk in sb.GetChunks())
  582. {
  583. await WriteAsync(chunk, ct).ConfigureAwait(false);
  584. }
  585. await WriteAsync(CoreNewLine, ct).ConfigureAwait(false);
  586. }
  587. }
  588. public Task WriteLineAsync(char[] buffer)
  589. {
  590. if (buffer == null)
  591. {
  592. return WriteLineAsync();
  593. }
  594. return WriteLineAsync(buffer, 0, buffer.Length);
  595. }
  596. public virtual Task WriteLineAsync(char[] buffer, int index, int count)
  597. {
  598. var tuple = new Tuple<TextWriter, char[], int, int>(this, buffer, index, count);
  599. return Task.Factory.StartNew(state =>
  600. {
  601. var t = (Tuple<TextWriter, char[], int, int>)state;
  602. t.Item1.WriteLine(t.Item2, t.Item3, t.Item4);
  603. },
  604. tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  605. }
  606. public virtual Task WriteLineAsync(ReadOnlyMemory<char> buffer, CancellationToken cancellationToken = default) =>
  607. cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) :
  608. MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ?
  609. WriteLineAsync(array.Array, array.Offset, array.Count) :
  610. Task.Factory.StartNew(state =>
  611. {
  612. var t = (Tuple<TextWriter, ReadOnlyMemory<char>>)state;
  613. t.Item1.WriteLine(t.Item2.Span);
  614. }, Tuple.Create(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  615. public virtual Task WriteLineAsync()
  616. {
  617. return WriteAsync(CoreNewLine);
  618. }
  619. public virtual Task FlushAsync()
  620. {
  621. return Task.Factory.StartNew(state =>
  622. {
  623. ((TextWriter)state).Flush();
  624. },
  625. this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  626. }
  627. #endregion
  628. private sealed class NullTextWriter : TextWriter
  629. {
  630. internal NullTextWriter() : base(CultureInfo.InvariantCulture)
  631. {
  632. }
  633. public override Encoding Encoding
  634. {
  635. get
  636. {
  637. return Encoding.Unicode;
  638. }
  639. }
  640. public override void Write(char[] buffer, int index, int count)
  641. {
  642. }
  643. public override void Write(string value)
  644. {
  645. }
  646. // Not strictly necessary, but for perf reasons
  647. public override void WriteLine()
  648. {
  649. }
  650. // Not strictly necessary, but for perf reasons
  651. public override void WriteLine(string value)
  652. {
  653. }
  654. public override void WriteLine(object value)
  655. {
  656. }
  657. public override void Write(char value)
  658. {
  659. }
  660. }
  661. public static TextWriter Synchronized(TextWriter writer)
  662. {
  663. if (writer == null)
  664. throw new ArgumentNullException(nameof(writer));
  665. return writer is SyncTextWriter ? writer : new SyncTextWriter(writer);
  666. }
  667. internal sealed class SyncTextWriter : TextWriter, IDisposable
  668. {
  669. private readonly TextWriter _out;
  670. internal SyncTextWriter(TextWriter t) : base(t.FormatProvider)
  671. {
  672. _out = t;
  673. }
  674. public override Encoding Encoding => _out.Encoding;
  675. public override IFormatProvider FormatProvider => _out.FormatProvider;
  676. public override string NewLine
  677. {
  678. [MethodImpl(MethodImplOptions.Synchronized)]
  679. get { return _out.NewLine; }
  680. [MethodImpl(MethodImplOptions.Synchronized)]
  681. set { _out.NewLine = value; }
  682. }
  683. [MethodImpl(MethodImplOptions.Synchronized)]
  684. public override void Close() => _out.Close();
  685. [MethodImpl(MethodImplOptions.Synchronized)]
  686. protected override void Dispose(bool disposing)
  687. {
  688. // Explicitly pick up a potentially methodimpl'ed Dispose
  689. if (disposing)
  690. ((IDisposable)_out).Dispose();
  691. }
  692. [MethodImpl(MethodImplOptions.Synchronized)]
  693. public override ValueTask DisposeAsync()
  694. {
  695. return _out.DisposeAsync();
  696. }
  697. [MethodImpl(MethodImplOptions.Synchronized)]
  698. public override void Flush() => _out.Flush();
  699. [MethodImpl(MethodImplOptions.Synchronized)]
  700. public override void Write(char value) => _out.Write(value);
  701. [MethodImpl(MethodImplOptions.Synchronized)]
  702. public override void Write(char[] buffer) => _out.Write(buffer);
  703. [MethodImpl(MethodImplOptions.Synchronized)]
  704. public override void Write(char[] buffer, int index, int count) => _out.Write(buffer, index, count);
  705. [MethodImpl(MethodImplOptions.Synchronized)]
  706. public override void Write(bool value) => _out.Write(value);
  707. [MethodImpl(MethodImplOptions.Synchronized)]
  708. public override void Write(int value) => _out.Write(value);
  709. [MethodImpl(MethodImplOptions.Synchronized)]
  710. public override void Write(uint value) => _out.Write(value);
  711. [MethodImpl(MethodImplOptions.Synchronized)]
  712. public override void Write(long value) => _out.Write(value);
  713. [MethodImpl(MethodImplOptions.Synchronized)]
  714. public override void Write(ulong value) => _out.Write(value);
  715. [MethodImpl(MethodImplOptions.Synchronized)]
  716. public override void Write(float value) => _out.Write(value);
  717. [MethodImpl(MethodImplOptions.Synchronized)]
  718. public override void Write(double value) => _out.Write(value);
  719. [MethodImpl(MethodImplOptions.Synchronized)]
  720. public override void Write(decimal value) => _out.Write(value);
  721. [MethodImpl(MethodImplOptions.Synchronized)]
  722. public override void Write(string value) => _out.Write(value);
  723. [MethodImpl(MethodImplOptions.Synchronized)]
  724. public override void Write(StringBuilder value) => _out.Write(value);
  725. [MethodImpl(MethodImplOptions.Synchronized)]
  726. public override void Write(object value) => _out.Write(value);
  727. [MethodImpl(MethodImplOptions.Synchronized)]
  728. public override void Write(string format, object arg0) => _out.Write(format, arg0);
  729. [MethodImpl(MethodImplOptions.Synchronized)]
  730. public override void Write(string format, object arg0, object arg1) => _out.Write(format, arg0, arg1);
  731. [MethodImpl(MethodImplOptions.Synchronized)]
  732. public override void Write(string format, object arg0, object arg1, object arg2) => _out.Write(format, arg0, arg1, arg2);
  733. [MethodImpl(MethodImplOptions.Synchronized)]
  734. public override void Write(string format, object[] arg) => _out.Write(format, arg);
  735. [MethodImpl(MethodImplOptions.Synchronized)]
  736. public override void WriteLine() => _out.WriteLine();
  737. [MethodImpl(MethodImplOptions.Synchronized)]
  738. public override void WriteLine(char value) => _out.WriteLine(value);
  739. [MethodImpl(MethodImplOptions.Synchronized)]
  740. public override void WriteLine(decimal value) => _out.WriteLine(value);
  741. [MethodImpl(MethodImplOptions.Synchronized)]
  742. public override void WriteLine(char[] buffer) => _out.WriteLine(buffer);
  743. [MethodImpl(MethodImplOptions.Synchronized)]
  744. public override void WriteLine(char[] buffer, int index, int count) => _out.WriteLine(buffer, index, count);
  745. [MethodImpl(MethodImplOptions.Synchronized)]
  746. public override void WriteLine(bool value) => _out.WriteLine(value);
  747. [MethodImpl(MethodImplOptions.Synchronized)]
  748. public override void WriteLine(int value) => _out.WriteLine(value);
  749. [MethodImpl(MethodImplOptions.Synchronized)]
  750. public override void WriteLine(uint value) => _out.WriteLine(value);
  751. [MethodImpl(MethodImplOptions.Synchronized)]
  752. public override void WriteLine(long value) => _out.WriteLine(value);
  753. [MethodImpl(MethodImplOptions.Synchronized)]
  754. public override void WriteLine(ulong value) => _out.WriteLine(value);
  755. [MethodImpl(MethodImplOptions.Synchronized)]
  756. public override void WriteLine(float value) => _out.WriteLine(value);
  757. [MethodImpl(MethodImplOptions.Synchronized)]
  758. public override void WriteLine(double value) => _out.WriteLine(value);
  759. [MethodImpl(MethodImplOptions.Synchronized)]
  760. public override void WriteLine(string value) => _out.WriteLine(value);
  761. [MethodImpl(MethodImplOptions.Synchronized)]
  762. public override void WriteLine(StringBuilder value) => _out.WriteLine(value);
  763. [MethodImpl(MethodImplOptions.Synchronized)]
  764. public override void WriteLine(object value) => _out.WriteLine(value);
  765. [MethodImpl(MethodImplOptions.Synchronized)]
  766. public override void WriteLine(string format, object arg0) => _out.WriteLine(format, arg0);
  767. [MethodImpl(MethodImplOptions.Synchronized)]
  768. public override void WriteLine(string format, object arg0, object arg1) => _out.WriteLine(format, arg0, arg1);
  769. [MethodImpl(MethodImplOptions.Synchronized)]
  770. public override void WriteLine(string format, object arg0, object arg1, object arg2) => _out.WriteLine(format, arg0, arg1, arg2);
  771. [MethodImpl(MethodImplOptions.Synchronized)]
  772. public override void WriteLine(string format, object[] arg) => _out.WriteLine(format, arg);
  773. //
  774. // On SyncTextWriter all APIs should run synchronously, even the async ones.
  775. //
  776. [MethodImpl(MethodImplOptions.Synchronized)]
  777. public override Task WriteAsync(char value)
  778. {
  779. Write(value);
  780. return Task.CompletedTask;
  781. }
  782. [MethodImpl(MethodImplOptions.Synchronized)]
  783. public override Task WriteAsync(string value)
  784. {
  785. Write(value);
  786. return Task.CompletedTask;
  787. }
  788. [MethodImpl(MethodImplOptions.Synchronized)]
  789. public override Task WriteAsync(StringBuilder value, CancellationToken cancellationToken = default)
  790. {
  791. Write(value);
  792. return Task.CompletedTask;
  793. }
  794. [MethodImpl(MethodImplOptions.Synchronized)]
  795. public override Task WriteAsync(char[] buffer, int index, int count)
  796. {
  797. Write(buffer, index, count);
  798. return Task.CompletedTask;
  799. }
  800. [MethodImpl(MethodImplOptions.Synchronized)]
  801. public override Task WriteLineAsync(char value)
  802. {
  803. WriteLine(value);
  804. return Task.CompletedTask;
  805. }
  806. [MethodImpl(MethodImplOptions.Synchronized)]
  807. public override Task WriteLineAsync(string value)
  808. {
  809. WriteLine(value);
  810. return Task.CompletedTask;
  811. }
  812. [MethodImpl(MethodImplOptions.Synchronized)]
  813. public override Task WriteLineAsync(StringBuilder value, CancellationToken cancellationToken = default)
  814. {
  815. WriteLine(value);
  816. return Task.CompletedTask;
  817. }
  818. [MethodImpl(MethodImplOptions.Synchronized)]
  819. public override Task WriteLineAsync(char[] buffer, int index, int count)
  820. {
  821. WriteLine(buffer, index, count);
  822. return Task.CompletedTask;
  823. }
  824. [MethodImpl(MethodImplOptions.Synchronized)]
  825. public override Task FlushAsync()
  826. {
  827. Flush();
  828. return Task.CompletedTask;
  829. }
  830. }
  831. }
  832. }