/
githubmirror
/
PowerShell
Обзор
Документация
Войти
/
githubmirror
/
PowerShell
Код
Запросы
0
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
src/System.Management.Automation/engine/AsyncByteStreamTransfer.cs
83 строки
2 KB
Patrick Meinecke
Support byte stream piping between native commands and file redirection (#17857)
28 апр 2023, 03:17
Не верифицирован
28 апр 2023, 03:17
2424ad8
Код
Авторство
О чём код?
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #nullable enable using System.Buffers; using System.IO; using System.Threading; using System.Threading.Tasks; namespace System.Management.Automation; /// <summary> /// Represents the transfer of bytes from one <see cref="Stream" /> to another /// asynchronously. /// </summary> internal sealed class AsyncByteStreamTransfer : IDisposable { private const int DefaultBufferSize = 1024; private readonly BytePipe _bytePipe; private readonly BytePipe _destinationPipe; private readonly Memory<byte> _buffer; private readonly CancellationTokenSource _cts = new(); private Task? _readToBufferTask; public AsyncByteStreamTransfer( BytePipe bytePipe, BytePipe destinationPipe) { _bytePipe = bytePipe; _destinationPipe = destinationPipe; _buffer = new byte[DefaultBufferSize]; } public Task EOF => _readToBufferTask ?? Task.CompletedTask; public void BeginReadChunks() { _readToBufferTask = Task.Run(ReadBufferAsync); } public void Dispose() => _cts.Cancel(); private async Task ReadBufferAsync() { Stream stream; Stream? destinationStream = null; try { stream = await _bytePipe.GetStream(_cts.Token); destinationStream = await _destinationPipe.GetStream(_cts.Token); while (true) { int bytesRead; bytesRead = await stream.ReadAsync(_buffer, _cts.Token); if (bytesRead is 0) { break; } destinationStream.Write(_buffer.Span.Slice(0, bytesRead)); } } catch (IOException) { return; } catch (OperationCanceledException) { return; } finally { destinationStream?.Close(); } } }