System.IO.Stream.WriteAsync(byte[], int, int, System.Threading.CancellationToken)

Here are the examples of the csharp api System.IO.Stream.WriteAsync(byte[], int, int, System.Threading.CancellationToken) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

587 Examples 7

19 View Source File : DeviceStreamSample.cs
License : MIT License
Project Creator : Azure-Samples

private static async Task HandleIncomingDataAsync(NetworkStream localStream, ClientWebSocket remoteStream, CancellationToken cancellationToken)
        {
            byte[] receiveBuffer = new byte[10240];

            while (localStream.CanRead)
            {
                var receiveResult = await remoteStream.ReceiveAsync(receiveBuffer, cancellationToken).ConfigureAwait(false);

                await localStream.WriteAsync(receiveBuffer, 0, receiveResult.Count).ConfigureAwait(false);
            }
        }

19 View Source File : ThrottledStream.cs
License : MIT License
Project Creator : bezzad

public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
            await Throttle(count).ConfigureAwait(false);
            await _baseStream.WriteAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false);
        }

19 View Source File : VideoAnalyzer.cs
License : MIT License
Project Creator : AlturosDestinations

private async Task<replacedyzeResult> GetVideoInfoAsync(MediaInput mediaInput, CancellationToken cancellationToken = default)
        {
            if (!File.Exists(this._ffprobePath))
            {
                return new replacedyzeResult { Successful = false, ErrorMessage = $"ffprobe could not be found {this._ffprobePath}" };
            }

            var startInfo = new ProcessStartInfo
            {
                FileName = this._ffprobePath,
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true,
            };

            if (mediaInput.FileContent != null)
            {
                startInfo.RedirectStandardInput = true;
                startInfo.Arguments = $"-v quiet -print_format json -show_format -show_streams -";
            }
            else
            {
                startInfo.Arguments = $"-v quiet -print_format json -show_format -show_streams \"{mediaInput.FilePath}\"";
            }

            using (var outputWaitHandle = new AutoResetEvent(false))
            {
                var json = new StringBuilder();

                var dataReceived = new DataReceivedEventHandler((sender, e) =>
                {
                    if (e.Data == null)
                    {
                        outputWaitHandle.Set();
                        return;
                    }

                    json.AppendLine(e.Data);
                });

                this._process = new Process();

                try
                {
                    this._process.StartInfo = startInfo;
                    this._process.OutputDataReceived += dataReceived;

                    if (!this._process.Start())
                    {
                        return new replacedyzeResult { ErrorMessage = "Cannot start ffprobe" };
                    }

                    this._process.BeginOutputReadLine();

                    if (mediaInput.FileContent != null)
                    {
                        using (var ffprobeIn = this._process.StandardInput.BaseStream)
                        {
                            var packageSize = 100000;
                            for (var i = 0; i < mediaInput.FileContent.Length; i += packageSize)
                            {
                                var package = mediaInput.FileContent.Skip(i).Take(packageSize).ToArray();
                                await ffprobeIn.WriteAsync(package, 0, package.Length, cancellationToken);
                            }
                            await ffprobeIn.FlushAsync(cancellationToken);
                            ffprobeIn.Close();
                        }
                    }

                    if (!this._process.WaitForExit(this._timeout) || !outputWaitHandle.WaitOne(this._timeout))
                    {
                        return new replacedyzeResult { ErrorMessage = $"Timeout reached {this._timeout} (ms)" };
                    }

                    var videoInfo = JsonConvert.DeserializeObject<VideoInfoResult>(json.ToString(), this._jsonSerializerSettings);
                    if (videoInfo.Format == null && videoInfo.Streams == null)
                    {
                        return new replacedyzeResult { Successful = false, ErrorMessage = "No feedback from ffprobe" };
                    }

                    return new replacedyzeResult { Successful = true, VideoInfo = videoInfo };
                }
                catch (IOException)
                {
                    var videoInfo = JsonConvert.DeserializeObject<VideoInfoResult>(json.ToString(), this._jsonSerializerSettings);
                    if (videoInfo.Format == null && videoInfo.Streams == null)
                    {
                        return new replacedyzeResult { Successful = false, ErrorMessage = "No feedback from ffprobe (IOException)" };
                    }

                    return new replacedyzeResult { Successful = true, VideoInfo = videoInfo };
                }
                catch (Exception exception)
                {
                    return new replacedyzeResult { Successful = false, ErrorMessage = exception.ToString() };
                }
                finally
                {
                    this._process.OutputDataReceived -= dataReceived;
                    this._process?.Dispose();
                }
            }
        }

19 View Source File : OwinResponse.cs
License : Apache License 2.0
Project Creator : aspnet

public virtual Task WriteAsync(byte[] data, int offset, int count, CancellationToken token)
        {
            return Body.WriteAsync(data, offset, count, token);
        }

19 View Source File : ChunkingPipeline.cs
License : Apache License 2.0
Project Creator : apache

private async ValueTask SendBuffer()
    {
        if (_bufferCount != 0)
        {
#if NETSTANDARD2_0
            await _stream.WriteAsync(_buffer, 0, _bufferCount).ConfigureAwait(false);
#else
            await _stream.WriteAsync(_buffer.AsMemory(0, _bufferCount)).ConfigureAwait(false);
#endif
            _bufferCount = 0;
        }
    }

19 View Source File : TcpServer.cs
License : MIT License
Project Creator : alexwahl

private async Task ListenForClientConnection(CancellationToken ct)
        {
            this.tcpListener.Start();
            ct.Register(CancelComm);

            while (!ct.IsCancellationRequested)
            {
                //blocks until a client has connected to the server
                TcpClient client = await this.tcpListener.AcceptTcpClientAsync();

                //only one client can connect !
                NetworkStream clientStream = client.GetStream();
                
                Connection_established();

                
                byte[] message = new byte[4096];
                int bytesRead;

                while (!ct.IsCancellationRequested)
                {
                    try
                    {
                        bytesRead = 0;
                        //read message from client
                        bytesRead = await clientStream.ReadAsync(message, 0, 4096, ct).ConfigureAwait(true);
                        var str = System.Text.Encoding.Default.GetString(message, 0,bytesRead);
                        var answer = rigctrl.ExecCommand(str);
                        var answerBytes = (new System.Text.ASCIIEncoding()).GetBytes(answer);
                        await clientStream.WriteAsync(answerBytes, 0, answerBytes.Length,ct).ConfigureAwait(true);
                        
                    }
                    catch
                    {
                        
                        //a socket error has occured
                        break;
                    }
                }
                client.Close();
                connection_lost();
            }
        }

19 View Source File : X11Client.cs
License : MIT License
Project Creator : azyobuzin

protected internal async Task SendRequestAsync(int requestSize, Action<byte[]> createRequest)
        {
            var tcs = new TaskCompletionSource<Unit>();
            ushort sequenceNumber = 0;

            Task mainReplyAction(byte[] replyHeader, byte[] replyContent, Exception exception)
            {
                tcs.SetException(exception ?? new InvalidOperationException("Received an unexpected reply."));
                return Task.CompletedTask;
            }

            Task syncReplyAction(byte[] replyHeader, byte[] replyContent, Exception exception)
            {
                Debug.replacedert(sequenceNumber > 0);
                this._replyActions.TryRemove(sequenceNumber, out var _);

                if (exception == null)
                {
                    tcs.TrySetResult(Unit.Default);
                }
                else
                {
                    tcs.TrySetException(exception);
                }

                return Task.CompletedTask;
            }

            void createSyncRequest(byte[] buf)
            {
                ref var req = ref Unsafe.As<byte, EmptyRequestHeader>(ref buf[0]);
                req = default;
                req.Opcode = 43;
                req.RequestLength = 1;
            }

            await this._requestSemapreplaced.WaitAsync().ConfigureAwait(false);
            try
            {
                // 1. リクエストを送信
                sequenceNumber = this._sequenceNumber;
                if (!this._replyActions.TryAdd(sequenceNumber, mainReplyAction))
                    throw new InvalidOperationException("Duplicated sequence number");

                EnsureBufferSize(ref this._requestBuffer, requestSize);
                createRequest(this._requestBuffer);
                await this.Stream.WriteAsync(this._requestBuffer, 0, requestSize).ConfigureAwait(false);

                this._sequenceNumber++;

                // 2. 次のリクエストのリプライが返ってくる前に 1 へのエラーが返ってくるんじゃねえかなぁ
                if (!this._replyActions.TryAdd((ushort)(sequenceNumber + 1), syncReplyAction))
                    throw new InvalidOperationException("Duplicated sequence number");

                // _requestBuffer は最低 8192 あるから EnsureBufferSize は要らない
                createSyncRequest(this._requestBuffer);
                await this.Stream.WriteAsync(this._requestBuffer, 0, EmptyRequestHeaderSize).ConfigureAwait(false);

                this._sequenceNumber++;
            }
            catch
            {
                if (sequenceNumber > 0)
                {
                    this._replyActions.TryRemove(sequenceNumber, out var _);
                    this._replyActions.TryRemove((ushort)(sequenceNumber + 1), out var _);
                }
            }
            finally
            {
                this._requestSemapreplaced.Release();
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : adospace

private static async Task<bool> SendreplacedemblyToEmulatorAsync(string replacedemblyPath, bool debugging = true)
        {
            
            //ThreadHelper.ThrowIfNotOnUIThread();

            //outputPane.OutputString($"Sending to emulator new replacedembly (debugging={debugging})...");
            //outputPane.Activate(); // Brings this pane into view

            var client = new TcpClient
            {
                ReceiveTimeout = 15000,
                SendTimeout = 15000
            };

            try
            {
               
                await client.ConnectAsync(IPAddress.Loopback, 45820);

                var replacedemblyRaw = await FileUtil.ReadAllFileAsync(replacedemblyPath);

                var networkStream = client.GetStream();

                var lengthBytes = BitConverter.GetBytes(replacedemblyRaw.Length);
                await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                await networkStream.WriteAsync(replacedemblyRaw, 0, replacedemblyRaw.Length);

                await networkStream.FlushAsync();

                var replacedemblySymbolStorePath = Path.Combine(Path.GetDirectoryName(replacedemblyPath), Path.GetFileNameWithoutExtension(replacedemblyPath) + ".pdb");

                if (File.Exists(replacedemblySymbolStorePath) && debugging)
                {
                    var replacedemblySynmbolStoreRaw = await FileUtil.ReadAllFileAsync(replacedemblySymbolStorePath);

                    lengthBytes = BitConverter.GetBytes(replacedemblySynmbolStoreRaw.Length);

                    await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                    await networkStream.WriteAsync(replacedemblySynmbolStoreRaw, 0, replacedemblySynmbolStoreRaw.Length);

                    await networkStream.FlushAsync();
                }
                else
                {
                    lengthBytes = BitConverter.GetBytes(0);

                    await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                    await networkStream.FlushAsync();
                }

                var booleanBuffer = new byte[1];
                if (await networkStream.ReadAsync(booleanBuffer, 0, 1) == 0)
                    throw new SocketException();

                Console.WriteLine($"Sent new replacedembly ({replacedemblyRaw.Length} bytes) to emulator{Environment.NewLine}");
            }
            catch (Exception ex)
            {
                Console.WriteLine([email protected]"
Unable to connect to ReactorUI Hot Reload module
Please ensure that:
1) Only one device is running among emulators and physical devices
2) Application is running either in debug or release mode
3) RxApplication call WithHotReload()
Socket exception: {ex.Message}
");
                return false;
            }
            finally
            {
                client.Close();
            }

            return true;
        }

19 View Source File : BlockCryptoStream.cs
License : MIT License
Project Creator : BlazorPlus

public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
			{
				if (count > MAX_BLOCK_SIZE)
				{
					for (int start = 0; start < count; start += MAX_BLOCK_SIZE)
					{
						int len = Math.Min(MAX_BLOCK_SIZE, count - start);
						await WriteAsync(buffer, offset + start, len, cancellationToken);
					}
					return;
				}

				byte[] outputdata = new byte[count + 32];
				int outputlen = 0;
				using (MemoryStream bs = new MemoryStream(outputdata))
				{
					byte[] cntbytes = BitConverter.GetBytes((int)count);
					bs.Write(cntbytes);
					Array.Reverse(cntbytes);
					bs.Write(cntbytes);
					bs.Write(cntbytes);//use for rest size

					using var trans = _tdes.CreateEncryptor();
					using (CryptoStream cs = new CryptoStream(bs, trans, CryptoStreamMode.Write))
					{
						cs.Write(cntbytes);//prefix 
						cs.Write(buffer, offset, count);
						Array.Reverse(cntbytes);
						cs.FlushFinalBlock();

						outputlen = (int)bs.Position;
					}

				}

				Buffer.BlockCopy(BitConverter.GetBytes((int)outputlen), 0, outputdata, 8, 4);

				//Console.WriteLine("MemoryStream : " + outputdata.Length + " , " + outputlen + " , " + count);

				//var msg = await CommandMessage.ReadFromStreamAsync(new MemoryStream(buffer, offset, count));
				//Console.WriteLine("MemoryStream : " + msg);

				//BlockCryptoStream test = CreateDecryptReader(new MemoryStream(outputdata, 0, outputlen), _tdes);
				//byte[] testdata = new byte[count];
				//int rc = await test.ReadAsync(testdata, 0, testdata.Length);
				//Console.WriteLine("MemoryStream TESTED : " + count + "/" + rc + " : " + testdata.SequenceEqual(new Memory<byte>(buffer, offset, count).ToArray()));

				//Console.WriteLine("MemoryStream : " + BitConverter.ToString(outputdata, 0, outputlen));

				await _inner.WriteAsync(outputdata, 0, outputlen, cancellationToken);
			}

19 View Source File : PooledByteBufferWriter.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : agocke

internal Task WriteToStreamAsync(Stream destination, CancellationToken cancellationToken)
        {
            return destination.WriteAsync(_rentedBuffer, 0, _index, cancellationToken);
        }

19 View Source File : Extensions.cs
License : MIT License
Project Creator : arqueror

public static async Task CopyToAsync(this Stream source, Stream destination,
            IProgress<double> progress = null, CancellationToken cancellationToken = default,
            int bufferSize = 81920)
        {
            var buffer = new byte[bufferSize];
            var totalBytesCopied = 0L;
            int bytesCopied;

            do
            {
                // Read
                bytesCopied = await source.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);

                // Write
                await destination.WriteAsync(buffer, 0, bytesCopied, cancellationToken).ConfigureAwait(false);

                // Report progress
                totalBytesCopied += bytesCopied;
                progress?.Report(1.0 * totalBytesCopied / source.Length);
            } while (bytesCopied > 0);
        }

19 View Source File : ModbusRtuSerialPort.cs
License : GNU Lesser General Public License v3.0
Project Creator : Apollo3zehn

public async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken token)
        {
            using var timeoutCts = new CancellationTokenSource(_serialPort.WriteTimeout);

            /* _serialPort.DiscardInBuffer is essential here to cancel the operation */
            using (timeoutCts.Token.Register(() => _serialPort.DiscardOutBuffer()))
            using (token.Register(() => timeoutCts.Cancel()))
            {
                try
                {
                    await _serialPort.BaseStream.WriteAsync(buffer, offset, count, timeoutCts.Token);
                }
                catch (OperationCanceledException) when (token.IsCancellationRequested)
                {
                    throw;
                }
                catch (OperationCanceledException) when (timeoutCts.IsCancellationRequested)
                {
                    throw new TimeoutException("The asynchronous write operation timed out.");
                }
                catch (IOException) when (timeoutCts.IsCancellationRequested && !token.IsCancellationRequested)
                {
                    throw new TimeoutException("The asynchronous write operation timed out.");
                }
            }
        }

19 View Source File : ProgressStreamContent.cs
License : MIT License
Project Creator : alexrainman

public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
            {
                token.ThrowIfCancellationRequested();

                var linked = CancellationTokenSource.CreateLinkedTokenSource(token, cancellationToken);
                var task = ParentStream.WriteAsync(buffer, offset, count, linked.Token);

                WriteCallback(count);
                return task;
            }

19 View Source File : HttpClientProgressExtensions.cs
License : GNU General Public License v3.0
Project Creator : AutoDarkMode

static async Task CopyToAsync (this Stream source, Stream destination, int bufferSize, IProgress<long> progress = null, CancellationToken cancellationToken = default (CancellationToken))
		{
			if (bufferSize < 0)
				throw new ArgumentOutOfRangeException (nameof (bufferSize));
			if (source is null)
				throw new ArgumentNullException (nameof (source));
			if (!source.CanRead)
				throw new InvalidOperationException ($"'{nameof (source)}' is not readable.");
			if (destination == null)
				throw new ArgumentNullException (nameof (destination));
			if (!destination.CanWrite)
				throw new InvalidOperationException ($"'{nameof (destination)}' is not writable.");

			var buffer = new byte[bufferSize];
			long totalBytesRead = 0;
			int bytesRead;
			while ((bytesRead = await source.ReadAsync (buffer, 0, buffer.Length, cancellationToken).ConfigureAwait (false)) != 0) {
				await destination.WriteAsync (buffer, 0, bytesRead, cancellationToken).ConfigureAwait (false);
				totalBytesRead += bytesRead;
				progress?.Report (totalBytesRead);
			}
		}

19 View Source File : StreamString.cs
License : MIT License
Project Creator : actions

public async Task WriteStringAsync(string outString, CancellationToken cancellationToken)
        {
            byte[] outBuffer = streamEncoding.GetBytes(outString);
            Int32 len = outBuffer.Length;
            if (len > MaxStringSize)
            {
                throw new ArgumentOutOfRangeException();
            }

            await WriteInt32Async(len, cancellationToken);
            cancellationToken.ThrowIfCancellationRequested();
            Task op = _ioStream.WriteAsync(outBuffer, 0, len, cancellationToken);
            await op.WithCancellation(cancellationToken);
            op = _ioStream.FlushAsync(cancellationToken);
            await op.WithCancellation(cancellationToken);
        }

19 View Source File : SchematizedMediaTypeFormatter.cs
License : MIT License
Project Creator : AzureAD

public override Task WriteToStreamAsync(
            Type type,
            object value,
            Stream writeStream,
            HttpContent content,
            TransportContext transportContext,
            CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            if (null == type)
            {
                throw new ArgumentNullException(nameof(type));
            }

            if (null == writeStream)
            {
                throw new ArgumentNullException(nameof(writeStream));
            }

            Func<byte[], Task> writeFunction =
                new Func<byte[], Task>(
                    async (byte[] buffer) =>
                        await writeStream.WriteAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false));
            Task result = this.WriteToStream(type, value, writeStream, writeFunction);
            return result;
        }

19 View Source File : MessagePackSerializer.cs
License : Apache License 2.0
Project Creator : allenai

public static async Task SerializeAsync<T>(Stream stream, T value, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();
            using (SequencePool.Rental sequenceRental = SequencePool.Shared.Rent())
            {
                Serialize<T>(sequenceRental.Value, value, options, cancellationToken);

                try
                {
                    foreach (ReadOnlyMemory<byte> segment in sequenceRental.Value.AsReadOnlySequence)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        await stream.WriteAsync(segment, cancellationToken).ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {
                    throw new MessagePackSerializationException("Error occurred while writing the serialized data to the stream.", ex);
                }
            }
        }

19 View Source File : PipeStream.cs
License : Apache License 2.0
Project Creator : beetlex-io

public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
            if (!SSLConfirmed && SSL)
            {
                return base.WriteAsync(buffer, offset, count, cancellationToken);
            }
            else
            {
                Write(buffer, offset, count);
                return Task.CompletedTask;
            }
        }

19 View Source File : TcpClientEx.cs
License : MIT License
Project Creator : 1iveowl

public static async Task SendStringAsync(this Stream stream, string text, CancellationToken ct)
        {
            var frame = Encoding.UTF8.GetBytes(text);
            await stream.WriteAsync(frame, 0, frame.Length, ct);
        }

19 View Source File : DanmakuClient.cs
License : GNU General Public License v3.0
Project Creator : Bililive

private static async Task SendMessageAsync(Stream stream, int action, string body = "")
        {
            if (stream is null)
                throw new ArgumentNullException(nameof(stream));

            var playload = Encoding.UTF8.GetBytes(body);
            var size = playload.Length + 16;
            var buffer = ArrayPool<byte>.Shared.Rent(16);
            try
            {
                BinaryPrimitives.WriteUInt32BigEndian(new Span<byte>(buffer, 0, 4), (uint)size);
                BinaryPrimitives.WriteUInt16BigEndian(new Span<byte>(buffer, 4, 2), 16);
                BinaryPrimitives.WriteUInt16BigEndian(new Span<byte>(buffer, 6, 2), 1);
                BinaryPrimitives.WriteUInt32BigEndian(new Span<byte>(buffer, 8, 4), (uint)action);
                BinaryPrimitives.WriteUInt32BigEndian(new Span<byte>(buffer, 12, 4), 1);

                await stream.WriteAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
                if (playload.Length > 0)
                    await stream.WriteAsync(playload, 0, playload.Length).ConfigureAwait(false);
                await stream.FlushAsync().ConfigureAwait(false);
            }
            finally
            {
                ArrayPool<byte>.Shared.Return(buffer);
            }
        }

19 View Source File : ModbusServer.cs
License : MIT License
Project Creator : AndreasAmMueller

private async Task HandleClient(TcpClient client)
		{
			logger?.LogTrace("ModbusServer.HandleClient enter");
			var endpoint = (IPEndPoint)client.Client.RemoteEndPoint;
			try
			{
				ClientConnected?.Invoke(this, new ClientEventArgs(endpoint));
				logger?.LogInformation($"Client connected: {endpoint.Address}.");

				var stream = client.GetStream();
				while (!stopCts.IsCancellationRequested)
				{
					using var requestStream = new MemoryStream();

					using (var cts = new CancellationTokenSource(Timeout))
					using (stopCts.Token.Register(() => cts.Cancel()))
					{
						try
						{
							byte[] header = await stream.ReadExpectedBytes(6, cts.Token);
							await requestStream.WriteAsync(header, 0, header.Length, cts.Token);

							byte[] bytes = header.Skip(4).Take(2).ToArray();
							if (BitConverter.IsLittleEndian)
								Array.Reverse(bytes);

							int following = BitConverter.ToUInt16(bytes, 0);
							byte[] payload = await stream.ReadExpectedBytes(following, cts.Token);
							await requestStream.WriteAsync(payload, 0, payload.Length, cts.Token);
						}
						catch (OperationCanceledException) when (cts.IsCancellationRequested)
						{
							continue;
						}
					}

					try
					{
						var request = new Request(requestStream.GetBuffer());
						var response = requestHandler?.Invoke(request, stopCts.Token);
						if (response != null)
						{
							using var cts = new CancellationTokenSource(Timeout);
							using var reg = stopCts.Token.Register(() => cts.Cancel());
							try
							{
								byte[] bytes = response.Serialize();
								await stream.WriteAsync(bytes, 0, bytes.Length, cts.Token);
							}
							catch (OperationCanceledException) when (cts.IsCancellationRequested)
							{
								continue;
							}
						}
					}
					catch (ArgumentException ex)
					{
						logger?.LogWarning(ex, $"Invalid data received from {endpoint.Address}: {ex.Message}");
					}
					catch (NotImplementedException ex)
					{
						logger?.LogWarning(ex, $"Invalid data received from {endpoint.Address}: {ex.Message}");
					}
				}
			}
			catch (IOException)
			{
				// client connection closed
				return;
			}
			catch (Exception ex)
			{
				logger?.LogError(ex, $"Unexpected error ({ex.GetType().Name}) occurred: {ex.GetMessage()}");
			}
			finally
			{
				ClientDisconnected?.Invoke(this, new ClientEventArgs(endpoint));
				logger?.LogInformation($"Client disconnected: {endpoint.Address}");

				client.Dispose();
				tcpClients.TryRemove(client, out _);

				logger?.LogTrace("ModbusServer.HandleClient leave");
			}
		}

19 View Source File : Extensions.cs
License : MIT License
Project Creator : AndreasAmMueller

public static async Task WriteAsync(this SerialPort serialPort, byte[] buffer, int offset, int count, CancellationToken cancellationToken)
		{
			// serial port read/write timeouts seem to be ignored, so ensure the timeouts.
			using (var cts = new CancellationTokenSource(serialPort.WriteTimeout))
			using (cancellationToken.Register(() => cts.Cancel()))
			{
				var ctr = default(CancellationTokenRegistration);
				if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
				{
					// The async stream implementation on windows is a bit broken.
					// this kicks it back to us.
					ctr = cts.Token.Register(() => serialPort.DiscardOutBuffer());
				}

				try
				{
					await serialPort.BaseStream.WriteAsync(buffer, offset, count, cts.Token);
				}
				catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
				{
					cancellationToken.ThrowIfCancellationRequested();
				}
				catch (OperationCanceledException) when (cts.IsCancellationRequested)
				{
					throw new TimeoutException("No bytes written within the WriteTimeout.");
				}
				catch (IOException) when (cts.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
				{
					throw new TimeoutException("No bytes written within the WriteTimeout.");
				}
				finally
				{
					ctr.Dispose();
				}
			}
		}

19 View Source File : RedisIO.cs
License : MIT License
Project Creator : 2881099

async public Task<int> WriteAsync(RedisCommand command)
        {
            var data = _writer.Prepare(command);
            await Stream.WriteAsync(data, 0, data.Length);
            return data.Length;
            //var tcs = new TaskCompletionSource<int>();
            //lock (_streamLock)
            //{
            //    Stream.BeginWrite(data, 0, data.Length, asyncResult =>
            //    {
            //        try
            //        {
            //            _stream.EndWrite(asyncResult);
            //            tcs.TrySetResult(data.Length);
            //        }
            //        catch (Exception ex)
            //        {
            //            tcs.TrySetException(ex);
            //        }
            //    }, null);
            //    Stream.Flush();
            //}
            //return tcs.Task;
        }

19 View Source File : ChunkingPipeline.cs
License : Apache License 2.0
Project Creator : apache

private async ValueTask Send(ReadOnlyMemory<byte> memory)
    {
        await SendBuffer().ConfigureAwait(false);

#if NETSTANDARD2_0
        var data = memory.ToArray();
        await _stream.WriteAsync(data, 0, data.Length).ConfigureAwait(false);
#else
        await _stream.WriteAsync(memory).ConfigureAwait(false);
#endif
    }

19 View Source File : TweakableStream.cs
License : MIT License
Project Creator : airbreather

public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => _inner.WriteAsync(buffer, offset, count, cancellationToken);

19 View Source File : FtpClient.cs
License : MIT License
Project Creator : ARKlab

public override async Task UploadFileAsync(string path, byte[] content, CancellationToken ctk = default)
        {
            using (var cts = new CancellationTokenSource(TimeSpan.FromMinutes(5)))
            using (var linked = CancellationTokenSource.CreateLinkedTokenSource(ctk, cts.Token))
            {
                var rq = _createFtpRequest(path);
                try
                {
                    rq.Method = WebRequestMethods.Ftp.UploadFile;
                    rq.UseBinary = true;
                    rq.ContentLength = content.Length;

                    using (var ostrm = await rq.GetRequestStreamAsync())
                    {
                        await ostrm.WriteAsync(content, 0, content.Length, linked.Token);
                        await ostrm.FlushAsync(linked.Token);
                    }

                    using (var rs = rq.GetResponseAsync(linked.Token))
                    {
                    }
                }
                catch (WebException ex)
                {
                    if (ex.Response != null)
                        ex.Response.Dispose();
                    throw;
                }
                finally
                {
                    rq.Abort();
                }
            }
        }

19 View Source File : MetricsPrometheusProtobufOutputFormatter.cs
License : Apache License 2.0
Project Creator : AppMetrics

public Task WriteAsync(
            Stream output,
            MetricsDataValueSource metricsData,
            CancellationToken cancellationToken = default)
        {
            if (output == null)
            {
                throw new ArgumentNullException(nameof(output));
            }

            var bodyData = ProtoFormatter.Format(metricsData.GetPrometheusMetricsSnapshot(_options.MetricNameFormatter));
            return output.WriteAsync(bodyData, 0, bodyData.Length, cancellationToken);
        }

19 View Source File : Context.cs
License : MIT License
Project Creator : alexanderdna

private async Task writeAsync(Message msg)
        {
            var msgJson = Message.Serialize(msg);
            var stream = Client.GetStream();
            int pos = 0, nRemaining = msgJson.Length;
            while (nRemaining > 0 && ShouldDisconnect is false)
            {
                int bytesToCopy = Math.Min(outBuffer.Length, msgJson.Length - pos);
                for (int i = pos, j = 0, c = pos + bytesToCopy; i < c; ++i, ++j)
                {
                    outBuffer[j] = (byte)(msgJson[i] & 0x7f);
                }
                nRemaining -= bytesToCopy;
                pos += bytesToCopy;

                await stream.WriteAsync(outBuffer.AsMemory(0, bytesToCopy));
            }

            stream.WriteByte((byte)'\n');
            await stream.FlushAsync();
        }

19 View Source File : DelegatingStream.cs
License : Apache License 2.0
Project Creator : aspnet

public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
            return Stream.WriteAsync(buffer, offset, count, cancellationToken);
        }

19 View Source File : StreamString.cs
License : MIT License
Project Creator : actions

public async Task WriteInt32Async(Int32 value, CancellationToken cancellationToken)
        {
            byte[] int32Bytes = BitConverter.GetBytes(value);
            Task op = _ioStream.WriteAsync(int32Bytes, 0, sizeof(Int32), cancellationToken);
            await op.WithCancellation(cancellationToken);
        }

19 View Source File : ExceptionFilterStream.cs
License : Apache License 2.0
Project Creator : aspnet

public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
            try
            {
                FirstWrite();
                await _innerStream.WriteAsync(buffer, offset, count, cancellationToken);
            }
            catch (Exception ex)
            {
                Exception wrapped;
                if (TryWrapException(ex, out wrapped))
                {
                    throw wrapped;
                }

                throw;
            }
        }

19 View Source File : DnsClientBase.cs
License : Apache License 2.0
Project Creator : alexreinert

private async Task<QueryResponse> QueryByTcpAsync(IPAddress nameServer, byte[] messageData, int messageLength, TcpClient tcpClient, NetworkStream tcpStream, CancellationToken token)
		{
			if (!IsTcpEnabled)
				return null;

			try
			{
				if (tcpClient == null)
				{
					tcpClient = new TcpClient(nameServer.AddressFamily)
					{
						ReceiveTimeout = QueryTimeout,
						SendTimeout = QueryTimeout
					};

					if (!await tcpClient.TryConnectAsync(nameServer, _port, QueryTimeout, token))
					{
						return null;
					}

					tcpStream = tcpClient.GetStream();
				}

				int tmp = 0;
				byte[] lengthBuffer = new byte[2];

				if (messageLength > 0)
				{
					DnsMessageBase.EncodeUShort(lengthBuffer, ref tmp, (ushort) messageLength);

					await tcpStream.WriteAsync(lengthBuffer, 0, 2, token);
					await tcpStream.WriteAsync(messageData, 0, messageLength, token);
				}

				if (!await TryReadAsync(tcpClient, tcpStream, lengthBuffer, 2, token))
					return null;

				tmp = 0;
				int length = DnsMessageBase.ParseUShort(lengthBuffer, ref tmp);

				byte[] resultData = new byte[length];

				return await TryReadAsync(tcpClient, tcpStream, resultData, length, token) ? new QueryResponse(resultData, nameServer, tcpClient, tcpStream) : null;
			}
			catch (Exception e)
			{
				Trace.TraceError("Error on dns query: " + e);
				return null;
			}
		}

19 View Source File : ProcessExtensions.cs
License : Apache License 2.0
Project Creator : Azure-App-Service

private static async Task CopyStreamAsync(Stream from, Stream to, IdleManager idleManager, CancellationToken cancellationToken, bool closeAfterCopy = false)
        {
            try
            {
                byte[] bytes = new byte[1024];
                int read = 0;
                while ((read = await from.ReadAsync(bytes, 0, bytes.Length, cancellationToken)) != 0)
                {
                    idleManager.UpdateActivity();
                    await to.WriteAsync(bytes, 0, read, cancellationToken);
                }

                idleManager.UpdateActivity();
            }
            finally
            {
                // this is needed specifically for input stream
                // in order to tell executable that the input is done
                if (closeAfterCopy)
                {
                    to.Close();
                }
            }
        }

19 View Source File : TcpClientEx.cs
License : MIT License
Project Creator : 1iveowl

public static async Task SendDatagramAsync(this Stream stream, byte[] byteArray, CancellationToken ct)
        {
            await stream.WriteAsync(byteArray, 0, byteArray.Length, ct);
        }

19 View Source File : DeviceStreamSample.cs
License : MIT License
Project Creator : Azure-Samples

private static async Task HandleIncomingDataAsync(NetworkStream localStream, ClientWebSocket remoteStream, CancellationToken cancellationToken)
        {
            byte[] buffer = new byte[10240];

            while (remoteStream.State == WebSocketState.Open)
            {
                var receiveResult = await remoteStream.ReceiveAsync(buffer, cancellationToken).ConfigureAwait(false);

                await localStream.WriteAsync(buffer, 0, receiveResult.Count).ConfigureAwait(false);
            }
        }

19 View Source File : NativeMessagingHost.cs
License : MIT License
Project Creator : alexwiese

public async Task Write(object value)
        {
            var jsonString = JsonConvert.SerializeObject(value, _jsonSerializerSettings);

            // Use the encoding to get the length of the 
            // buffer, it may not be the number of chars
            var byteBuffer = _encoding.GetBytes(jsonString);
            var byteBufferLength = byteBuffer.Length;

            _sendLengthBuffer[0] = (byte)byteBufferLength;
            _sendLengthBuffer[1] = (byte)(byteBufferLength >> 8);
            _sendLengthBuffer[2] = (byte)(byteBufferLength >> 16);
            _sendLengthBuffer[3] = (byte)(byteBufferLength >> 24);

            // Send the buffer length (Int32) then the JSON
            await _outStream.WriteAsync(_sendLengthBuffer, 0, sizeof(int));
            await _outStream.WriteAsync(byteBuffer, 0, byteBufferLength);
        }

19 View Source File : X11Client.cs
License : MIT License
Project Creator : azyobuzin

private async Task SetupConnectionAsync()
        {
            byte[] createBuffer()
            {
                var b = new byte[8192]; // Connection Setup のレスポンスがでかい
                ref var req = ref Unsafe.As<byte, SetupRequestData>(ref b[0]);
                req.ByteOrder = BitConverter.IsLittleEndian ? (byte)0x6c : (byte)0x42;
                req.ProtocolMajorVersion = 11;
                req.ProtocolMinorVersion = 0;
                req.LengthOfAuthorizationProtocolName = 0;
                req.LengthOfAuthorizationProtocolData = 0;
                return b;
            }

            var buf = createBuffer();
            await this.Stream.WriteAsync(buf, 0, SetupRequestDataSize).ConfigureAwait(false);

            await this.ReadExactAsync(buf, SetupResponseHeaderSize).ConfigureAwait(false);

            var responseHeader = Unsafe.ReadUnaligned<SetupResponseHeader>(ref buf[0]);
            var additionalDataLength = responseHeader.LengthOfAdditionalData * 4;

            EnsureBufferSize(ref buf, additionalDataLength);
            this._requestBuffer = buf;

            await this.ReadExactAsync(buf, additionalDataLength).ConfigureAwait(false);

            switch (responseHeader.Status)
            {
                case 0: // Failed
                    throw new X11Exception(string.Format(
                        "The server (X{0}.{1}) refused the connection: {2}",
                        responseHeader.ProtocolMajorVersion,
                        responseHeader.ProtocolMinorVersion,
                        ReadString8(buf, 0, responseHeader.LengthOfReasonIfFailed)
                    ));
                case 2: // Authenticate
                    throw new X11Exception("Authentication is required: "
                        + ReadString8(buf, 0, additionalDataLength).TrimEnd('\0'));
                case 1: // Success
                    this.ReadSetupResponse(buf, additionalDataLength);
                    break;
                default:
                    throw new X11Exception("Unexpected response status");
            }
        }

19 View Source File : HotReloadCommand.cs
License : MIT License
Project Creator : adospace

private static async Task<bool> SendreplacedemblyToEmulatorAsync(ProgressMonitor progressMonitor, string replacedemblyPath, bool debugging)
        {
            var client = new TcpClient
            {
                ReceiveTimeout = 15000,
                SendTimeout = 15000
            };

            try
            {
                await client.ConnectAsync(IPAddress.Loopback, 45820);

                var replacedemblyRaw = await FileUtil.ReadAllFileAsync(replacedemblyPath);

                var networkStream = client.GetStream();

                var lengthBytes = BitConverter.GetBytes(replacedemblyRaw.Length);
                await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                await networkStream.WriteAsync(replacedemblyRaw, 0, replacedemblyRaw.Length);

                await networkStream.FlushAsync();

                var replacedemblySymbolStorePath = Path.Combine(Path.GetDirectoryName(replacedemblyPath), Path.GetFileNameWithoutExtension(replacedemblyPath) + ".pdb");

                if (File.Exists(replacedemblySymbolStorePath) && debugging)
                {
                    var replacedemblySynmbolStoreRaw = await FileUtil.ReadAllFileAsync(replacedemblySymbolStorePath);

                    lengthBytes = BitConverter.GetBytes(replacedemblySynmbolStoreRaw.Length);

                    await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                    await networkStream.WriteAsync(replacedemblySynmbolStoreRaw, 0, replacedemblySynmbolStoreRaw.Length);

                    await networkStream.FlushAsync();
                }
                else
                {
                    lengthBytes = BitConverter.GetBytes(0);

                    await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                    await networkStream.FlushAsync();
                }

                var booleanBuffer = new byte[1];
                if (await networkStream.ReadAsync(booleanBuffer, 0, 1) == 0)
                    throw new SocketException();

                await progressMonitor.Log.WriteLineAsync($"Sent new replacedembly ({replacedemblyRaw.Length} bytes) to emulator");
            }
            catch (Exception ex)
            {
                await progressMonitor.ErrorLog.WriteLineAsync([email protected]"
Unable to connect to ReactorUI Hot Reload module
Please ensure that:
1) Only one device is running among emulators and physical devices
2) Application is running either in debug or release mode
3) RxApplication call WithHotReload()
Socket exception: {ex.Message}");

                return false;
            }
            finally
            {
                client.Close();
            }

            return true;
        }

19 View Source File : StreamExtensions.cs
License : The Unlicense
Project Creator : BAndysc

public static async Task CopyToAsync(this Stream source, Stream destination, int bufferSize, IProgress<long>? progress = null, CancellationToken cancellationToken = default) {
            if (source == null)
                throw new ArgumentNullException(nameof(source));
            if (!source.CanRead)
                throw new ArgumentException("Has to be readable", nameof(source));
            if (destination == null)
                throw new ArgumentNullException(nameof(destination));
            if (!destination.CanWrite)
                throw new ArgumentException("Has to be writable", nameof(destination));
            if (bufferSize < 0)
                throw new ArgumentOutOfRangeException(nameof(bufferSize));

            var buffer = new byte[bufferSize];
            long totalBytesRead = 0;
            int bytesRead;
            while ((bytesRead = await source.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0) {
                await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
                totalBytesRead += bytesRead;
                progress?.Report(totalBytesRead);
            }
        }

19 View Source File : StreamPolyfillExtensions.cs
License : Apache License 2.0
Project Creator : allenai

internal static async ValueTask WriteAsync(this Stream stream, ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            var sharedBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length);
            try
            {
                buffer.CopyTo(sharedBuffer);
                await stream.WriteAsync(sharedBuffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);
            }
            finally
            {
                ArrayPool<byte>.Shared.Return(sharedBuffer);
            }
        }

19 View Source File : PipeStream.cs
License : Apache License 2.0
Project Creator : beetlex-io

public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (!SSLConfirmed && SSL)
            {
                return base.WriteAsync(buffer, cancellationToken);
            }
            else
            {
                Write(buffer.Span);
                return new ValueTask();
            }
        }

19 View Source File : CosmosItem.cs
License : MIT License
Project Creator : 1iveowl

public virtual async Task<Stream> ToStream(string parreplacedionKeyHeader, string parreplacedionKey, CancellationToken ct = default)
        {
            // Using NewtonSoft Json.NET here to utilize the ContractResolver option.
            var customJsonSerializer = new JsonSerializerSettings
            {
                ContractResolver = new ParreplacedionKeyContractResolver<T>(parreplacedionKeyHeader, nameof(REPLACE_WITH_PARreplacedION_KEY_HEADER))
            };

            REPLACE_WITH_PARreplacedION_KEY_HEADER = parreplacedionKey;

            var cosmosItemJson = JsonConvert.SerializeObject(this, Formatting.None, customJsonSerializer);

            await _memoryStream.WriteAsync(Encoding.UTF8.GetBytes(cosmosItemJson), ct);

            return _memoryStream;
        }

19 View Source File : TagExtentions.cs
License : GNU General Public License v3.0
Project Creator : Bililive

public static async Task WriteTo(this Tag tag, Stream target, int timestamp, IMemoryStreamProvider? memoryStreamProvider = null)
        {
            var buffer = ArrayPool<byte>.Shared.Rent(11);
            var dispose = true;
            Stream? data = null;
            try
            {
                if (tag.IsScript())
                {
                    if (tag.ScriptData is null)
                        throw new Exception("BinaryData is null");

                    data = memoryStreamProvider?.CreateMemoryStream(nameof(TagExtentions) + ":" + nameof(WriteTo) + ":TagBodyTemp") ?? new MemoryStream();
                    tag.ScriptData.WriteTo(data);
                }
                else if (tag.Nalus != null)
                {
                    if (tag.BinaryData is null)
                        throw new Exception("BinaryData is null");

                    data = memoryStreamProvider?.CreateMemoryStream(nameof(TagExtentions) + ":" + nameof(WriteTo) + ":TagBodyTemp") ?? new MemoryStream();

                    tag.BinaryData.Seek(0, SeekOrigin.Begin);

                    tag.BinaryData.Read(buffer, 0, 5);
                    data.Write(buffer, 0, 5);

                    foreach (var nalu in tag.Nalus)
                    {
                        BinaryPrimitives.WriteUInt32BigEndian(new Span<byte>(buffer, 0, 4), nalu.FullSize);
                        data.Write(buffer, 0, 4);

                        tag.BinaryData.Seek(nalu.StartPosition, SeekOrigin.Begin);
                        await tag.BinaryData.CopyBytesAsync(data, nalu.FullSize).ConfigureAwait(false);
                    }
                }
                else
                {
                    if (tag.BinaryData is null)
                        throw new Exception("BinaryData is null");

                    dispose = false;
                    data = tag.BinaryData;
                }

                data.Seek(0, SeekOrigin.Begin);

                BinaryPrimitives.WriteUInt32BigEndian(new Span<byte>(buffer, 0, 4), (uint)data.Length);
                buffer[0] = (byte)tag.Type;

                unsafe
                {
                    var stackTemp = stackalloc byte[4];
                    BinaryPrimitives.WriteInt32BigEndian(new Span<byte>(stackTemp, 4), timestamp);
                    buffer[4] = stackTemp[1];
                    buffer[5] = stackTemp[2];
                    buffer[6] = stackTemp[3];
                    buffer[7] = stackTemp[0];
                }

                buffer[8] = 0;
                buffer[9] = 0;
                buffer[10] = 0;

                await target.WriteAsync(buffer, 0, 11).ConfigureAwait(false);
                await data.CopyToAsync(target).ConfigureAwait(false);

                BinaryPrimitives.WriteUInt32BigEndian(new Span<byte>(buffer, 0, 4), (uint)data.Length + 11);
                await target.WriteAsync(buffer, 0, 4).ConfigureAwait(false);
            }
            finally
            {
                ArrayPool<byte>.Shared.Return(buffer);
                if (dispose)
                    data?.Dispose();
            }
        }

19 View Source File : ModbusClient.cs
License : MIT License
Project Creator : AndreasAmMueller

private async Task<Response> SendRequest(Request request, CancellationToken cancellationToken)
		{
			try
			{
				logger?.LogTrace("ModbusClient.SendRequest enter");
				CheckDisposed();

				lock (reconnectLock)
				{
					if (!IsConnected)
					{
						if (!isReconnecting)
							ConnectingTask = GetReconnectTask(true);

						throw new InvalidOperationException("Modbus client is not connected");
					}
				}

				if (stream == null)
					throw new InvalidOperationException("Modbus client failed to open stream");

				using var sendCts = CancellationTokenSource.CreateLinkedTokenSource(stopCts.Token, cancellationToken);
				
				var queueItem = new QueuedRequest
				{
					TaskCompletionSource = new TaskCompletionSource<Response>()
				};

				lock (trxIdLock)
				{
					queueItem.TransactionId = transactionId++;
				}

				await queueLock.WaitAsync(sendCts.Token);
				try
				{
					awaitingResponses.Add(queueItem);
					logger?.LogDebug($"Added transaction #{queueItem.TransactionId} to receive queue");
				}
				finally
				{
					queueLock.Release();
				}

				await sendLock.WaitAsync(sendCts.Token);
				try
				{
					request.TransactionId = queueItem.TransactionId;
					logger?.LogDebug($"Sending {request}");

					byte[] bytes = request.Serialize();
					using var timeCts = new CancellationTokenSource(SendTimeout);
					using var cts = CancellationTokenSource.CreateLinkedTokenSource(stopCts.Token, timeCts.Token, cancellationToken);
					try
					{
						await stream.WriteAsync(bytes, 0, bytes.Length, cts.Token);
						logger?.LogDebug($"Request for transaction #{request.TransactionId} sent");

						queueItem.TimeoutCancellationTokenSource = new CancellationTokenSource(ReceiveTimeout);
						queueItem.CancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(stopCts.Token, cancellationToken, queueItem.TimeoutCancellationTokenSource.Token);
						queueItem.Registration = queueItem.CancellationTokenSource.Token.Register(() => RemoveQueuedItem(queueItem));
					}
					catch (OperationCanceledException) when (timeCts.IsCancellationRequested)
					{
						queueItem.TaskCompletionSource.TrySetCanceled();
						await queueLock.WaitAsync(stopCts.Token);
						try
						{
							awaitingResponses.Remove(queueItem);
						}
						finally
						{
							queueLock.Release();
						}
					}
				}
				catch (Exception ex)
				{
					logger?.LogError(ex, $"Unexpected error ({ex.GetType().Name}) on send: {ex.GetMessage()}");
					queueItem.TaskCompletionSource.TrySetException(ex);
					await queueLock.WaitAsync(stopCts.Token);
					try
					{
						awaitingResponses.Remove(queueItem);
					}
					finally
					{
						queueLock.Release();
					}
				}
				finally
				{
					sendLock.Release();
				}

				return await queueItem.TaskCompletionSource.Task;
			}
			finally
			{
				logger?.LogTrace("ModbusClient.SendRequest leave");
			}
		}

19 View Source File : ReloadCommand.cs
License : MIT License
Project Creator : adospace

private static async Task<bool> SendreplacedemblyToEmulatorAsync(string replacedemblyPath, IVsOutputWindowPane outputPane, bool debugging)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
            //ThreadHelper.ThrowIfNotOnUIThread();

            //outputPane.OutputString($"Sending to emulator new replacedembly (debugging={debugging})...");
            //outputPane.Activate(); // Brings this pane into view

            var client = new TcpClient
            {
                ReceiveTimeout = 15000,
                SendTimeout = 15000
            };

            try
            {
                await client.ConnectAsync(IPAddress.Loopback, 45820);

                var replacedemblyRaw = await FileUtil.ReadAllFileAsync(replacedemblyPath);

                var networkStream = client.GetStream();

                var lengthBytes = BitConverter.GetBytes(replacedemblyRaw.Length);
                await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);
                
                await networkStream.WriteAsync(replacedemblyRaw, 0, replacedemblyRaw.Length);

                await networkStream.FlushAsync();

                var replacedemblySymbolStorePath = Path.Combine(Path.GetDirectoryName(replacedemblyPath), Path.GetFileNameWithoutExtension(replacedemblyPath) + ".pdb");

                if (File.Exists(replacedemblySymbolStorePath) && debugging)
                {
                    var replacedemblySynmbolStoreRaw = await FileUtil.ReadAllFileAsync(replacedemblySymbolStorePath);

                    lengthBytes = BitConverter.GetBytes(replacedemblySynmbolStoreRaw.Length);

                    await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                    await networkStream.WriteAsync(replacedemblySynmbolStoreRaw, 0, replacedemblySynmbolStoreRaw.Length);

                    await networkStream.FlushAsync();
                }
                else
                {
                    lengthBytes = BitConverter.GetBytes(0);

                    await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                    await networkStream.FlushAsync();
                }

                var booleanBuffer = new byte[1];
                if (await networkStream.ReadAsync(booleanBuffer, 0, 1) == 0)
                    throw new SocketException();

                outputPane.OutputStringThreadSafe($"Sent new replacedembly ({replacedemblyRaw.Length} bytes) to emulator{Environment.NewLine}");
            }
            catch (Exception ex)
            {
                outputPane.OutputStringThreadSafe([email protected]"
Unable to connect to ReactorUI Hot Reload module
Please ensure that:
1) Only one device is running among emulators and physical devices
2) Application is running either in debug or release mode
3) RxApplication call WithHotReload()
Socket exception: {ex.Message}
");
                return false;
            }
            finally
            {
                client.Close();
            }

            return true;
        }

19 View Source File : DisposeActionStream.cs
License : MIT License
Project Creator : 0x0ade

public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => Inner.WriteAsync(buffer, offset, count, cancellationToken);

19 View Source File : TcpClientEx.cs
License : MIT License
Project Creator : 1iveowl

public static async Task SendStringLineAsync(this Stream stream, string text, CancellationToken ct)
        {
            var frame = Encoding.UTF8.GetBytes($"{text}\r\n");
            await stream.WriteAsync(frame, 0, frame.Length, ct);
        }

19 View Source File : SliceStream.cs
License : MIT License
Project Creator : abdullin

public override Task CopyToAsync(Stream destination, int bufferSize, System.Threading.CancellationToken cancellationToken)
		{
			Contract.Ensures(m_position >= 0 && m_position <= m_slice.Count);

			if (destination == null) throw new ArgumentNullException("destination");
			if (!destination.CanWrite) throw new ArgumentException("The destination stream cannot be written to", "destination");

			int remaining = m_slice.Count - m_position;
			if (remaining <= 0) return TaskHelpers.CompletedTask;

			// simulate the read
			m_position += remaining;

			// we can write everyting in one go, so just call WriteAsync and return that
			return destination.WriteAsync(m_slice.Array, m_slice.Offset, remaining, cancellationToken);
		}

19 View Source File : TweakableStream.cs
License : MIT License
Project Creator : airbreather

public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default) => _inner.WriteAsync(buffer, cancellationToken);

19 View Source File : CloudEventBatchContent.cs
License : MIT License
Project Creator : arcus-azure

private static async Task EncodeStringToStreamAsync(Stream stream, string input, CancellationToken cancellationToken)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(input);
            await stream.WriteAsync(buffer, 0, buffer.Length, cancellationToken);
        }

See More Examples