2
0

TextWriter.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978
  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. IFormattable f = value as IFormattable;
  257. if (f != null)
  258. {
  259. Write(f.ToString(null, FormatProvider));
  260. }
  261. else
  262. Write(value.ToString());
  263. }
  264. }
  265. /// <summary>
  266. /// Equivalent to Write(stringBuilder.ToString()) however it uses the
  267. /// StringBuilder.GetChunks() method to avoid creating the intermediate string
  268. /// </summary>
  269. /// <param name="value">The string (as a StringBuilder) to write to the stream</param>
  270. public virtual void Write(StringBuilder value)
  271. {
  272. if (value != null)
  273. {
  274. foreach (ReadOnlyMemory<char> chunk in value.GetChunks())
  275. Write(chunk);
  276. }
  277. }
  278. // Writes out a formatted string. Uses the same semantics as
  279. // string.Format.
  280. //
  281. public virtual void Write(string format, object arg0)
  282. {
  283. Write(string.Format(FormatProvider, format, arg0));
  284. }
  285. // Writes out a formatted string. Uses the same semantics as
  286. // string.Format.
  287. //
  288. public virtual void Write(string format, object arg0, object arg1)
  289. {
  290. Write(string.Format(FormatProvider, format, arg0, arg1));
  291. }
  292. // Writes out a formatted string. Uses the same semantics as
  293. // string.Format.
  294. //
  295. public virtual void Write(string format, object arg0, object arg1, object arg2)
  296. {
  297. Write(string.Format(FormatProvider, format, arg0, arg1, arg2));
  298. }
  299. // Writes out a formatted string. Uses the same semantics as
  300. // string.Format.
  301. //
  302. public virtual void Write(string format, params object[] arg)
  303. {
  304. Write(string.Format(FormatProvider, format, arg));
  305. }
  306. // Writes a line terminator to the text stream. The default line terminator
  307. // is Environment.NewLine, but this value can be changed by setting the NewLine property.
  308. //
  309. public virtual void WriteLine()
  310. {
  311. Write(CoreNewLine);
  312. }
  313. // Writes a character followed by a line terminator to the text stream.
  314. //
  315. public virtual void WriteLine(char value)
  316. {
  317. Write(value);
  318. WriteLine();
  319. }
  320. // Writes an array of characters followed by a line terminator to the text
  321. // stream.
  322. //
  323. public virtual void WriteLine(char[] buffer)
  324. {
  325. Write(buffer);
  326. WriteLine();
  327. }
  328. // Writes a range of a character array followed by a line terminator to the
  329. // text stream.
  330. //
  331. public virtual void WriteLine(char[] buffer, int index, int count)
  332. {
  333. Write(buffer, index, count);
  334. WriteLine();
  335. }
  336. public virtual void WriteLine(ReadOnlySpan<char> buffer)
  337. {
  338. char[] array = ArrayPool<char>.Shared.Rent(buffer.Length);
  339. try
  340. {
  341. buffer.CopyTo(new Span<char>(array));
  342. WriteLine(array, 0, buffer.Length);
  343. }
  344. finally
  345. {
  346. ArrayPool<char>.Shared.Return(array);
  347. }
  348. }
  349. // Writes the text representation of a boolean followed by a line
  350. // terminator to the text stream.
  351. //
  352. public virtual void WriteLine(bool value)
  353. {
  354. Write(value);
  355. WriteLine();
  356. }
  357. // Writes the text representation of an integer followed by a line
  358. // terminator to the text stream.
  359. //
  360. public virtual void WriteLine(int value)
  361. {
  362. Write(value);
  363. WriteLine();
  364. }
  365. // Writes the text representation of an unsigned integer followed by
  366. // a line terminator to the text stream.
  367. //
  368. [CLSCompliant(false)]
  369. public virtual void WriteLine(uint value)
  370. {
  371. Write(value);
  372. WriteLine();
  373. }
  374. // Writes the text representation of a long followed by a line terminator
  375. // to the text stream.
  376. //
  377. public virtual void WriteLine(long value)
  378. {
  379. Write(value);
  380. WriteLine();
  381. }
  382. // Writes the text representation of an unsigned long followed by
  383. // a line terminator to the text stream.
  384. //
  385. [CLSCompliant(false)]
  386. public virtual void WriteLine(ulong value)
  387. {
  388. Write(value);
  389. WriteLine();
  390. }
  391. // Writes the text representation of a float followed by a line terminator
  392. // to the text stream.
  393. //
  394. public virtual void WriteLine(float value)
  395. {
  396. Write(value);
  397. WriteLine();
  398. }
  399. // Writes the text representation of a double followed by a line terminator
  400. // to the text stream.
  401. //
  402. public virtual void WriteLine(double value)
  403. {
  404. Write(value);
  405. WriteLine();
  406. }
  407. public virtual void WriteLine(decimal value)
  408. {
  409. Write(value);
  410. WriteLine();
  411. }
  412. // Writes a string followed by a line terminator to the text stream.
  413. //
  414. public virtual void WriteLine(string value)
  415. {
  416. if (value != null)
  417. {
  418. Write(value);
  419. }
  420. Write(CoreNewLineStr);
  421. }
  422. /// <summary>
  423. /// Equivalent to WriteLine(stringBuilder.ToString()) however it uses the
  424. /// StringBuilder.GetChunks() method to avoid creating the intermediate string
  425. /// </summary>
  426. public virtual void WriteLine(StringBuilder value)
  427. {
  428. Write(value);
  429. WriteLine();
  430. }
  431. // Writes the text representation of an object followed by a line
  432. // terminator to the text stream.
  433. //
  434. public virtual void WriteLine(object value)
  435. {
  436. if (value == null)
  437. {
  438. WriteLine();
  439. }
  440. else
  441. {
  442. // Call WriteLine(value.ToString), not Write(Object), WriteLine().
  443. // This makes calls to WriteLine(Object) atomic.
  444. IFormattable f = value as IFormattable;
  445. if (f != null)
  446. {
  447. WriteLine(f.ToString(null, FormatProvider));
  448. }
  449. else
  450. {
  451. WriteLine(value.ToString());
  452. }
  453. }
  454. }
  455. // Writes out a formatted string and a new line. Uses the same
  456. // semantics as string.Format.
  457. //
  458. public virtual void WriteLine(string format, object arg0)
  459. {
  460. WriteLine(string.Format(FormatProvider, format, arg0));
  461. }
  462. // Writes out a formatted string and a new line. Uses the same
  463. // semantics as string.Format.
  464. //
  465. public virtual void WriteLine(string format, object arg0, object arg1)
  466. {
  467. WriteLine(string.Format(FormatProvider, format, arg0, arg1));
  468. }
  469. // Writes out a formatted string and a new line. Uses the same
  470. // semantics as string.Format.
  471. //
  472. public virtual void WriteLine(string format, object arg0, object arg1, object arg2)
  473. {
  474. WriteLine(string.Format(FormatProvider, format, arg0, arg1, arg2));
  475. }
  476. // Writes out a formatted string and a new line. Uses the same
  477. // semantics as string.Format.
  478. //
  479. public virtual void WriteLine(string format, params object[] arg)
  480. {
  481. WriteLine(string.Format(FormatProvider, format, arg));
  482. }
  483. #region Task based Async APIs
  484. public virtual Task WriteAsync(char value)
  485. {
  486. var tuple = new Tuple<TextWriter, char>(this, value);
  487. return Task.Factory.StartNew(state =>
  488. {
  489. var t = (Tuple<TextWriter, char>)state;
  490. t.Item1.Write(t.Item2);
  491. },
  492. tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  493. }
  494. public virtual Task WriteAsync(string value)
  495. {
  496. var tuple = new Tuple<TextWriter, string>(this, value);
  497. return Task.Factory.StartNew(state =>
  498. {
  499. var t = (Tuple<TextWriter, string>)state;
  500. t.Item1.Write(t.Item2);
  501. },
  502. tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  503. }
  504. /// <summary>
  505. /// Equivalent to WriteAsync(stringBuilder.ToString()) however it uses the
  506. /// StringBuilder.GetChunks() method to avoid creating the intermediate string
  507. /// </summary>
  508. /// <param name="value">The string (as a StringBuilder) to write to the stream</param>
  509. public virtual Task WriteAsync(StringBuilder value, CancellationToken cancellationToken = default)
  510. {
  511. return
  512. cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) :
  513. value == null ? Task.CompletedTask :
  514. WriteAsyncCore(value, cancellationToken);
  515. async Task WriteAsyncCore(StringBuilder sb, CancellationToken ct)
  516. {
  517. foreach (ReadOnlyMemory<char> chunk in sb.GetChunks())
  518. {
  519. await WriteAsync(chunk, ct).ConfigureAwait(false);
  520. }
  521. }
  522. }
  523. public Task WriteAsync(char[] buffer)
  524. {
  525. if (buffer == null)
  526. {
  527. return Task.CompletedTask;
  528. }
  529. return WriteAsync(buffer, 0, buffer.Length);
  530. }
  531. public virtual Task WriteAsync(char[] buffer, int index, int count)
  532. {
  533. var tuple = new Tuple<TextWriter, char[], int, int>(this, buffer, index, count);
  534. return Task.Factory.StartNew(state =>
  535. {
  536. var t = (Tuple<TextWriter, char[], int, int>)state;
  537. t.Item1.Write(t.Item2, t.Item3, t.Item4);
  538. },
  539. tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  540. }
  541. public virtual Task WriteAsync(ReadOnlyMemory<char> buffer, CancellationToken cancellationToken = default) =>
  542. cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) :
  543. MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ?
  544. WriteAsync(array.Array, array.Offset, array.Count) :
  545. Task.Factory.StartNew(state =>
  546. {
  547. var t = (Tuple<TextWriter, ReadOnlyMemory<char>>)state;
  548. t.Item1.Write(t.Item2.Span);
  549. }, Tuple.Create(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  550. public virtual Task WriteLineAsync(char value)
  551. {
  552. var tuple = new Tuple<TextWriter, char>(this, value);
  553. return Task.Factory.StartNew(state =>
  554. {
  555. var t = (Tuple<TextWriter, char>)state;
  556. t.Item1.WriteLine(t.Item2);
  557. },
  558. tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  559. }
  560. public virtual Task WriteLineAsync(string value)
  561. {
  562. var tuple = new Tuple<TextWriter, string>(this, value);
  563. return Task.Factory.StartNew(state =>
  564. {
  565. var t = (Tuple<TextWriter, string>)state;
  566. t.Item1.WriteLine(t.Item2);
  567. },
  568. tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  569. }
  570. /// <summary>
  571. /// Equivalent to WriteLineAsync(stringBuilder.ToString()) however it uses the
  572. /// StringBuilder.GetChunks() method to avoid creating the intermediate string
  573. /// </summary>
  574. /// <param name="value">The string (as a StringBuilder) to write to the stream</param>
  575. public virtual Task WriteLineAsync(StringBuilder value, CancellationToken cancellationToken = default)
  576. {
  577. return
  578. cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) :
  579. value == null ? WriteAsync(CoreNewLine, cancellationToken) :
  580. WriteLineAsyncCore(value, cancellationToken);
  581. async Task WriteLineAsyncCore(StringBuilder sb, CancellationToken ct)
  582. {
  583. foreach (ReadOnlyMemory<char> chunk in sb.GetChunks())
  584. {
  585. await WriteAsync(chunk, ct).ConfigureAwait(false);
  586. }
  587. await WriteAsync(CoreNewLine, ct).ConfigureAwait(false);
  588. }
  589. }
  590. public Task WriteLineAsync(char[] buffer)
  591. {
  592. if (buffer == null)
  593. {
  594. return WriteLineAsync();
  595. }
  596. return WriteLineAsync(buffer, 0, buffer.Length);
  597. }
  598. public virtual Task WriteLineAsync(char[] buffer, int index, int count)
  599. {
  600. var tuple = new Tuple<TextWriter, char[], int, int>(this, buffer, index, count);
  601. return Task.Factory.StartNew(state =>
  602. {
  603. var t = (Tuple<TextWriter, char[], int, int>)state;
  604. t.Item1.WriteLine(t.Item2, t.Item3, t.Item4);
  605. },
  606. tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  607. }
  608. public virtual Task WriteLineAsync(ReadOnlyMemory<char> buffer, CancellationToken cancellationToken = default) =>
  609. cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) :
  610. MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ?
  611. WriteLineAsync(array.Array, array.Offset, array.Count) :
  612. Task.Factory.StartNew(state =>
  613. {
  614. var t = (Tuple<TextWriter, ReadOnlyMemory<char>>)state;
  615. t.Item1.WriteLine(t.Item2.Span);
  616. }, Tuple.Create(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  617. public virtual Task WriteLineAsync()
  618. {
  619. return WriteAsync(CoreNewLine);
  620. }
  621. public virtual Task FlushAsync()
  622. {
  623. return Task.Factory.StartNew(state =>
  624. {
  625. ((TextWriter)state).Flush();
  626. },
  627. this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  628. }
  629. #endregion
  630. private sealed class NullTextWriter : TextWriter
  631. {
  632. internal NullTextWriter() : base(CultureInfo.InvariantCulture)
  633. {
  634. }
  635. public override Encoding Encoding
  636. {
  637. get
  638. {
  639. return Encoding.Unicode;
  640. }
  641. }
  642. public override void Write(char[] buffer, int index, int count)
  643. {
  644. }
  645. public override void Write(string value)
  646. {
  647. }
  648. // Not strictly necessary, but for perf reasons
  649. public override void WriteLine()
  650. {
  651. }
  652. // Not strictly necessary, but for perf reasons
  653. public override void WriteLine(string value)
  654. {
  655. }
  656. public override void WriteLine(object value)
  657. {
  658. }
  659. public override void Write(char value)
  660. {
  661. }
  662. }
  663. public static TextWriter Synchronized(TextWriter writer)
  664. {
  665. if (writer == null)
  666. throw new ArgumentNullException(nameof(writer));
  667. return writer is SyncTextWriter ? writer : new SyncTextWriter(writer);
  668. }
  669. internal sealed class SyncTextWriter : TextWriter, IDisposable
  670. {
  671. private readonly TextWriter _out;
  672. internal SyncTextWriter(TextWriter t) : base(t.FormatProvider)
  673. {
  674. _out = t;
  675. }
  676. public override Encoding Encoding => _out.Encoding;
  677. public override IFormatProvider FormatProvider => _out.FormatProvider;
  678. public override string NewLine
  679. {
  680. [MethodImpl(MethodImplOptions.Synchronized)]
  681. get { return _out.NewLine; }
  682. [MethodImpl(MethodImplOptions.Synchronized)]
  683. set { _out.NewLine = value; }
  684. }
  685. [MethodImpl(MethodImplOptions.Synchronized)]
  686. public override void Close() => _out.Close();
  687. [MethodImpl(MethodImplOptions.Synchronized)]
  688. protected override void Dispose(bool disposing)
  689. {
  690. // Explicitly pick up a potentially methodimpl'ed Dispose
  691. if (disposing)
  692. ((IDisposable)_out).Dispose();
  693. }
  694. [MethodImpl(MethodImplOptions.Synchronized)]
  695. public override ValueTask DisposeAsync()
  696. {
  697. return _out.DisposeAsync();
  698. }
  699. [MethodImpl(MethodImplOptions.Synchronized)]
  700. public override void Flush() => _out.Flush();
  701. [MethodImpl(MethodImplOptions.Synchronized)]
  702. public override void Write(char value) => _out.Write(value);
  703. [MethodImpl(MethodImplOptions.Synchronized)]
  704. public override void Write(char[] buffer) => _out.Write(buffer);
  705. [MethodImpl(MethodImplOptions.Synchronized)]
  706. public override void Write(char[] buffer, int index, int count) => _out.Write(buffer, index, count);
  707. [MethodImpl(MethodImplOptions.Synchronized)]
  708. public override void Write(bool value) => _out.Write(value);
  709. [MethodImpl(MethodImplOptions.Synchronized)]
  710. public override void Write(int value) => _out.Write(value);
  711. [MethodImpl(MethodImplOptions.Synchronized)]
  712. public override void Write(uint value) => _out.Write(value);
  713. [MethodImpl(MethodImplOptions.Synchronized)]
  714. public override void Write(long value) => _out.Write(value);
  715. [MethodImpl(MethodImplOptions.Synchronized)]
  716. public override void Write(ulong value) => _out.Write(value);
  717. [MethodImpl(MethodImplOptions.Synchronized)]
  718. public override void Write(float value) => _out.Write(value);
  719. [MethodImpl(MethodImplOptions.Synchronized)]
  720. public override void Write(double value) => _out.Write(value);
  721. [MethodImpl(MethodImplOptions.Synchronized)]
  722. public override void Write(decimal value) => _out.Write(value);
  723. [MethodImpl(MethodImplOptions.Synchronized)]
  724. public override void Write(string value) => _out.Write(value);
  725. [MethodImpl(MethodImplOptions.Synchronized)]
  726. public override void Write(StringBuilder value) => _out.Write(value);
  727. [MethodImpl(MethodImplOptions.Synchronized)]
  728. public override void Write(object value) => _out.Write(value);
  729. [MethodImpl(MethodImplOptions.Synchronized)]
  730. public override void Write(string format, object arg0) => _out.Write(format, arg0);
  731. [MethodImpl(MethodImplOptions.Synchronized)]
  732. public override void Write(string format, object arg0, object arg1) => _out.Write(format, arg0, arg1);
  733. [MethodImpl(MethodImplOptions.Synchronized)]
  734. public override void Write(string format, object arg0, object arg1, object arg2) => _out.Write(format, arg0, arg1, arg2);
  735. [MethodImpl(MethodImplOptions.Synchronized)]
  736. public override void Write(string format, object[] arg) => _out.Write(format, arg);
  737. [MethodImpl(MethodImplOptions.Synchronized)]
  738. public override void WriteLine() => _out.WriteLine();
  739. [MethodImpl(MethodImplOptions.Synchronized)]
  740. public override void WriteLine(char value) => _out.WriteLine(value);
  741. [MethodImpl(MethodImplOptions.Synchronized)]
  742. public override void WriteLine(decimal value) => _out.WriteLine(value);
  743. [MethodImpl(MethodImplOptions.Synchronized)]
  744. public override void WriteLine(char[] buffer) => _out.WriteLine(buffer);
  745. [MethodImpl(MethodImplOptions.Synchronized)]
  746. public override void WriteLine(char[] buffer, int index, int count) => _out.WriteLine(buffer, index, count);
  747. [MethodImpl(MethodImplOptions.Synchronized)]
  748. public override void WriteLine(bool value) => _out.WriteLine(value);
  749. [MethodImpl(MethodImplOptions.Synchronized)]
  750. public override void WriteLine(int value) => _out.WriteLine(value);
  751. [MethodImpl(MethodImplOptions.Synchronized)]
  752. public override void WriteLine(uint value) => _out.WriteLine(value);
  753. [MethodImpl(MethodImplOptions.Synchronized)]
  754. public override void WriteLine(long value) => _out.WriteLine(value);
  755. [MethodImpl(MethodImplOptions.Synchronized)]
  756. public override void WriteLine(ulong value) => _out.WriteLine(value);
  757. [MethodImpl(MethodImplOptions.Synchronized)]
  758. public override void WriteLine(float value) => _out.WriteLine(value);
  759. [MethodImpl(MethodImplOptions.Synchronized)]
  760. public override void WriteLine(double value) => _out.WriteLine(value);
  761. [MethodImpl(MethodImplOptions.Synchronized)]
  762. public override void WriteLine(string value) => _out.WriteLine(value);
  763. [MethodImpl(MethodImplOptions.Synchronized)]
  764. public override void WriteLine(StringBuilder value) => _out.WriteLine(value);
  765. [MethodImpl(MethodImplOptions.Synchronized)]
  766. public override void WriteLine(object value) => _out.WriteLine(value);
  767. [MethodImpl(MethodImplOptions.Synchronized)]
  768. public override void WriteLine(string format, object arg0) => _out.WriteLine(format, arg0);
  769. [MethodImpl(MethodImplOptions.Synchronized)]
  770. public override void WriteLine(string format, object arg0, object arg1) => _out.WriteLine(format, arg0, arg1);
  771. [MethodImpl(MethodImplOptions.Synchronized)]
  772. public override void WriteLine(string format, object arg0, object arg1, object arg2) => _out.WriteLine(format, arg0, arg1, arg2);
  773. [MethodImpl(MethodImplOptions.Synchronized)]
  774. public override void WriteLine(string format, object[] arg) => _out.WriteLine(format, arg);
  775. //
  776. // On SyncTextWriter all APIs should run synchronously, even the async ones.
  777. //
  778. [MethodImpl(MethodImplOptions.Synchronized)]
  779. public override Task WriteAsync(char value)
  780. {
  781. Write(value);
  782. return Task.CompletedTask;
  783. }
  784. [MethodImpl(MethodImplOptions.Synchronized)]
  785. public override Task WriteAsync(string value)
  786. {
  787. Write(value);
  788. return Task.CompletedTask;
  789. }
  790. [MethodImpl(MethodImplOptions.Synchronized)]
  791. public override Task WriteAsync(StringBuilder value, CancellationToken cancellationToken = default)
  792. {
  793. Write(value);
  794. return Task.CompletedTask;
  795. }
  796. [MethodImpl(MethodImplOptions.Synchronized)]
  797. public override Task WriteAsync(char[] buffer, int index, int count)
  798. {
  799. Write(buffer, index, count);
  800. return Task.CompletedTask;
  801. }
  802. [MethodImpl(MethodImplOptions.Synchronized)]
  803. public override Task WriteLineAsync(char value)
  804. {
  805. WriteLine(value);
  806. return Task.CompletedTask;
  807. }
  808. [MethodImpl(MethodImplOptions.Synchronized)]
  809. public override Task WriteLineAsync(string value)
  810. {
  811. WriteLine(value);
  812. return Task.CompletedTask;
  813. }
  814. [MethodImpl(MethodImplOptions.Synchronized)]
  815. public override Task WriteLineAsync(StringBuilder value, CancellationToken cancellationToken = default)
  816. {
  817. WriteLine(value);
  818. return Task.CompletedTask;
  819. }
  820. [MethodImpl(MethodImplOptions.Synchronized)]
  821. public override Task WriteLineAsync(char[] buffer, int index, int count)
  822. {
  823. WriteLine(buffer, index, count);
  824. return Task.CompletedTask;
  825. }
  826. [MethodImpl(MethodImplOptions.Synchronized)]
  827. public override Task FlushAsync()
  828. {
  829. Flush();
  830. return Task.CompletedTask;
  831. }
  832. }
  833. }
  834. }