TextWriter.cs 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  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 void Flush() => _out.Flush();
  694. [MethodImpl(MethodImplOptions.Synchronized)]
  695. public override void Write(char value) => _out.Write(value);
  696. [MethodImpl(MethodImplOptions.Synchronized)]
  697. public override void Write(char[] buffer) => _out.Write(buffer);
  698. [MethodImpl(MethodImplOptions.Synchronized)]
  699. public override void Write(char[] buffer, int index, int count) => _out.Write(buffer, index, count);
  700. [MethodImpl(MethodImplOptions.Synchronized)]
  701. public override void Write(ReadOnlySpan<char> buffer) => _out.Write(buffer);
  702. [MethodImpl(MethodImplOptions.Synchronized)]
  703. public override void Write(bool value) => _out.Write(value);
  704. [MethodImpl(MethodImplOptions.Synchronized)]
  705. public override void Write(int value) => _out.Write(value);
  706. [MethodImpl(MethodImplOptions.Synchronized)]
  707. public override void Write(uint value) => _out.Write(value);
  708. [MethodImpl(MethodImplOptions.Synchronized)]
  709. public override void Write(long value) => _out.Write(value);
  710. [MethodImpl(MethodImplOptions.Synchronized)]
  711. public override void Write(ulong value) => _out.Write(value);
  712. [MethodImpl(MethodImplOptions.Synchronized)]
  713. public override void Write(float value) => _out.Write(value);
  714. [MethodImpl(MethodImplOptions.Synchronized)]
  715. public override void Write(double value) => _out.Write(value);
  716. [MethodImpl(MethodImplOptions.Synchronized)]
  717. public override void Write(decimal value) => _out.Write(value);
  718. [MethodImpl(MethodImplOptions.Synchronized)]
  719. public override void Write(string value) => _out.Write(value);
  720. [MethodImpl(MethodImplOptions.Synchronized)]
  721. public override void Write(StringBuilder value) => _out.Write(value);
  722. [MethodImpl(MethodImplOptions.Synchronized)]
  723. public override void Write(object value) => _out.Write(value);
  724. [MethodImpl(MethodImplOptions.Synchronized)]
  725. public override void Write(string format, object arg0) => _out.Write(format, arg0);
  726. [MethodImpl(MethodImplOptions.Synchronized)]
  727. public override void Write(string format, object arg0, object arg1) => _out.Write(format, arg0, arg1);
  728. [MethodImpl(MethodImplOptions.Synchronized)]
  729. public override void Write(string format, object arg0, object arg1, object arg2) => _out.Write(format, arg0, arg1, arg2);
  730. [MethodImpl(MethodImplOptions.Synchronized)]
  731. public override void Write(string format, object[] arg) => _out.Write(format, arg);
  732. [MethodImpl(MethodImplOptions.Synchronized)]
  733. public override void WriteLine() => _out.WriteLine();
  734. [MethodImpl(MethodImplOptions.Synchronized)]
  735. public override void WriteLine(char value) => _out.WriteLine(value);
  736. [MethodImpl(MethodImplOptions.Synchronized)]
  737. public override void WriteLine(decimal value) => _out.WriteLine(value);
  738. [MethodImpl(MethodImplOptions.Synchronized)]
  739. public override void WriteLine(char[] buffer) => _out.WriteLine(buffer);
  740. [MethodImpl(MethodImplOptions.Synchronized)]
  741. public override void WriteLine(char[] buffer, int index, int count) => _out.WriteLine(buffer, index, count);
  742. [MethodImpl(MethodImplOptions.Synchronized)]
  743. public override void WriteLine(ReadOnlySpan<char> buffer) => _out.WriteLine(buffer);
  744. [MethodImpl(MethodImplOptions.Synchronized)]
  745. public override void WriteLine(bool value) => _out.WriteLine(value);
  746. [MethodImpl(MethodImplOptions.Synchronized)]
  747. public override void WriteLine(int value) => _out.WriteLine(value);
  748. [MethodImpl(MethodImplOptions.Synchronized)]
  749. public override void WriteLine(uint value) => _out.WriteLine(value);
  750. [MethodImpl(MethodImplOptions.Synchronized)]
  751. public override void WriteLine(long value) => _out.WriteLine(value);
  752. [MethodImpl(MethodImplOptions.Synchronized)]
  753. public override void WriteLine(ulong value) => _out.WriteLine(value);
  754. [MethodImpl(MethodImplOptions.Synchronized)]
  755. public override void WriteLine(float value) => _out.WriteLine(value);
  756. [MethodImpl(MethodImplOptions.Synchronized)]
  757. public override void WriteLine(double value) => _out.WriteLine(value);
  758. [MethodImpl(MethodImplOptions.Synchronized)]
  759. public override void WriteLine(string value) => _out.WriteLine(value);
  760. [MethodImpl(MethodImplOptions.Synchronized)]
  761. public override void WriteLine(StringBuilder value) => _out.WriteLine(value);
  762. [MethodImpl(MethodImplOptions.Synchronized)]
  763. public override void WriteLine(object value) => _out.WriteLine(value);
  764. [MethodImpl(MethodImplOptions.Synchronized)]
  765. public override void WriteLine(string format, object arg0) => _out.WriteLine(format, arg0);
  766. [MethodImpl(MethodImplOptions.Synchronized)]
  767. public override void WriteLine(string format, object arg0, object arg1) => _out.WriteLine(format, arg0, arg1);
  768. [MethodImpl(MethodImplOptions.Synchronized)]
  769. public override void WriteLine(string format, object arg0, object arg1, object arg2) => _out.WriteLine(format, arg0, arg1, arg2);
  770. [MethodImpl(MethodImplOptions.Synchronized)]
  771. public override void WriteLine(string format, object[] arg) => _out.WriteLine(format, arg);
  772. //
  773. // On SyncTextWriter all APIs should run synchronously, even the async ones.
  774. //
  775. [MethodImpl(MethodImplOptions.Synchronized)]
  776. public override ValueTask DisposeAsync()
  777. {
  778. Dispose();
  779. return default;
  780. }
  781. [MethodImpl(MethodImplOptions.Synchronized)]
  782. public override Task WriteAsync(char value)
  783. {
  784. Write(value);
  785. return Task.CompletedTask;
  786. }
  787. [MethodImpl(MethodImplOptions.Synchronized)]
  788. public override Task WriteAsync(string value)
  789. {
  790. Write(value);
  791. return Task.CompletedTask;
  792. }
  793. [MethodImpl(MethodImplOptions.Synchronized)]
  794. public override Task WriteAsync(StringBuilder value, CancellationToken cancellationToken = default)
  795. {
  796. if (cancellationToken.IsCancellationRequested)
  797. {
  798. return Task.FromCanceled(cancellationToken);
  799. }
  800. Write(value);
  801. return Task.CompletedTask;
  802. }
  803. [MethodImpl(MethodImplOptions.Synchronized)]
  804. public override Task WriteAsync(char[] buffer, int index, int count)
  805. {
  806. Write(buffer, index, count);
  807. return Task.CompletedTask;
  808. }
  809. [MethodImpl(MethodImplOptions.Synchronized)]
  810. public override Task WriteAsync(ReadOnlyMemory<char> buffer, CancellationToken cancellationToken = default)
  811. {
  812. if (cancellationToken.IsCancellationRequested)
  813. {
  814. return Task.FromCanceled(cancellationToken);
  815. }
  816. Write(buffer.Span);
  817. return Task.CompletedTask;
  818. }
  819. [MethodImpl(MethodImplOptions.Synchronized)]
  820. public override Task WriteLineAsync(ReadOnlyMemory<char> buffer, CancellationToken cancellationToken = default)
  821. {
  822. if (cancellationToken.IsCancellationRequested)
  823. {
  824. return Task.FromCanceled(cancellationToken);
  825. }
  826. WriteLine(buffer.Span);
  827. return Task.CompletedTask;
  828. }
  829. [MethodImpl(MethodImplOptions.Synchronized)]
  830. public override Task WriteLineAsync(char value)
  831. {
  832. WriteLine(value);
  833. return Task.CompletedTask;
  834. }
  835. [MethodImpl(MethodImplOptions.Synchronized)]
  836. public override Task WriteLineAsync()
  837. {
  838. WriteLine();
  839. return Task.CompletedTask;
  840. }
  841. [MethodImpl(MethodImplOptions.Synchronized)]
  842. public override Task WriteLineAsync(string value)
  843. {
  844. WriteLine(value);
  845. return Task.CompletedTask;
  846. }
  847. [MethodImpl(MethodImplOptions.Synchronized)]
  848. public override Task WriteLineAsync(StringBuilder value, CancellationToken cancellationToken = default)
  849. {
  850. if (cancellationToken.IsCancellationRequested)
  851. {
  852. return Task.FromCanceled(cancellationToken);
  853. }
  854. WriteLine(value);
  855. return Task.CompletedTask;
  856. }
  857. [MethodImpl(MethodImplOptions.Synchronized)]
  858. public override Task WriteLineAsync(char[] buffer, int index, int count)
  859. {
  860. WriteLine(buffer, index, count);
  861. return Task.CompletedTask;
  862. }
  863. [MethodImpl(MethodImplOptions.Synchronized)]
  864. public override Task FlushAsync()
  865. {
  866. Flush();
  867. return Task.CompletedTask;
  868. }
  869. }
  870. }
  871. }