本文整理汇总了C#中System.IO.Stream.EndWrite方法的典型用法代码示例。如果您正苦于以下问题:C# Stream.EndWrite方法的具体用法?C# Stream.EndWrite怎么用?C# Stream.EndWrite使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.Stream
的用法示例。
在下文中一共展示了Stream.EndWrite方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: WriteToStreamAsync
private static void WriteToStreamAsync(Stream s)
{
var t = Task.Factory.FromAsync(
(callback, state) => s.BeginWrite(new byte[] { 1, 2, 3 }, 0, 3, callback, state),
(ar) => s.EndWrite(ar),
null);
t.Wait();
}
示例2: CopyTo
// http://stackoverflow.com/questions/1540658/net-asynchronous-stream-read-write
public static void CopyTo(this Stream input, Stream output, int bufferSize)
{
if (!input.CanRead) throw new InvalidOperationException("input must be open for reading");
if (!output.CanWrite) throw new InvalidOperationException("output must be open for writing");
byte[][] buf = { new byte[bufferSize], new byte[bufferSize] };
int[] bufl = { 0, 0 };
int bufno = 0;
IAsyncResult read = input.BeginRead(buf[bufno], 0, buf[bufno].Length, null, null);
IAsyncResult write = null;
while (true) {
// wait for the read operation to complete
read.AsyncWaitHandle.WaitOne();
bufl[bufno] = input.EndRead(read);
// if zero bytes read, the copy is complete
if (bufl[bufno] == 0) {
break;
}
// wait for the in-flight write operation, if one exists, to complete
// the only time one won't exist is after the very first read operation completes
if (write != null) {
write.AsyncWaitHandle.WaitOne();
output.EndWrite(write);
}
// start the new write operation
write = output.BeginWrite(buf[bufno], 0, bufl[bufno], null, null);
// toggle the current, in-use buffer
// and start the read operation on the new buffer
bufno = (bufno == 0 ? 1 : 0);
read = input.BeginRead(buf[bufno], 0, buf[bufno].Length, null, null);
}
// wait for the final in-flight write operation, if one exists, to complete
// the only time one won't exist is if the input stream is empty.
if (write != null) {
write.AsyncWaitHandle.WaitOne();
output.EndWrite(write);
}
output.Flush();
// return to the caller ;
return;
}
示例3: SerializeToStreamAsync
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
var tcs = new TaskCompletionSource<object>();
_body.Invoke(
(data, callback) =>
{
if (data.Count == 0)
{
stream.Flush();
}
else if (callback == null)
{
stream.Write(data.Array, data.Offset, data.Count);
}
else
{
var sr = stream.BeginWrite(data.Array, data.Offset, data.Count, ar =>
{
if (!ar.CompletedSynchronously)
{
try { stream.EndWrite(ar); }
catch { }
try { callback.Invoke(); }
catch { }
}
}, null);
if (!sr.CompletedSynchronously)
{
return true;
}
stream.EndWrite(sr);
callback.Invoke();
}
return false;
},
ex =>
{
if (ex == null)
{
tcs.TrySetResult(null);
}
else
{
tcs.TrySetException(ex);
}
},
_cancellationToken);
return tcs.Task;
}
示例4: Pipe
/// <summary>
/// Pipes data from one stream to another
/// </summary>
/// <param name="input">Stream to read from</param>
/// <param name="output">Stream to write to</param>
/// <param name="MaxBufferSize">Size of buffer to use</param>
/// <returns>Number of bytes piped</returns>
public static int Pipe(Stream input, Stream output, int MaxBufferSize)
{
//Internal buffer are two buffers, each half of allowed buffer size, aligned to 1kb blocks
int bufferSize = (MaxBufferSize / 2) & ~1023;
if (bufferSize <= 0) throw new Exception("Specified buffer size to small");
byte[][] buffer = new byte[2][];
buffer[0] = new byte[bufferSize];
buffer[1] = new byte[bufferSize];
int currentBuffer = 0;
int r, total=0;
IAsyncResult asyncRead,asyncWrite;
//Read first block
r = input.Read(buffer[currentBuffer], 0, bufferSize);
//Continue while we're getting data
while (r > 0)
{
//read and write simultaneously
asyncWrite = output.BeginWrite(buffer[currentBuffer], 0, r, null, null);
asyncRead = input.BeginRead(buffer[1-currentBuffer], 0, bufferSize, null, null);
//Wait for both
output.EndWrite(asyncWrite);
r = input.EndRead(asyncRead);
//Switch buffers
currentBuffer = 1 - currentBuffer;
//Count bytes
total += r;
}
//Return number of bytes piped
return total;
}
示例5: AsyncCopy
public static WaitHandle AsyncCopy(this Stream src, Stream dst)
{
var evt = new ManualResetEvent(false);
var buffer = new byte[BUFFER_SIZE];
AsyncCallback cbk = null;
cbk = (asyncReadResult) =>
{
int bytesRead = src.EndRead(asyncReadResult);
if (bytesRead > 0)
{
//Console.Write("r");
dst.BeginWrite(buffer, 0, bytesRead,
(asyncWriteResult) =>
{
//Console.Write("w");
dst.EndWrite(asyncWriteResult);
src.BeginRead(buffer, 0, buffer.Length, cbk, null);
}, null);
}
else
{
Console.WriteLine();
dst.Flush();
dst.Position = 0;
evt.Set();
}
};
src.BeginRead(buffer, 0, buffer.Length, cbk, buffer);
return evt;
}
示例6: EndWrite
private static void EndWrite(Stream stream, IAsyncResult ar, byte[] buffer)
{
try
{
stream.EndWrite(ar);
}
catch (Exception)
{
stream.WriteAsync(buffer).Wait();
}
}
示例7: FinishWriteAsync
private static void FinishWriteAsync(Stream stream, IAsyncResult asyncResult, TaskCompletionSource<int> taskCompletionSource) {
try {
stream.EndWrite(asyncResult);
taskCompletionSource.SetResult(0);
}
catch (OperationCanceledException) {
taskCompletionSource.TrySetCanceled();
}
catch (Exception exception) {
taskCompletionSource.SetException(exception);
}
}
示例8: CreateFixedVhdFileAtAsync
private static IEnumerable<CompletionPort> CreateFixedVhdFileAtAsync(AsyncMachine machine, Stream destination, long virtualSize)
{
var footer = VhdFooterFactory.CreateFixedDiskFooter(virtualSize);
var serializer = new VhdFooterSerializer(footer);
var buffer = serializer.ToByteArray();
destination.SetLength(virtualSize + VhdConstants.VHD_FOOTER_SIZE);
destination.Seek(-VhdConstants.VHD_FOOTER_SIZE, SeekOrigin.End);
destination.BeginWrite(buffer, 0, buffer.Length, machine.CompletionCallback, null);
yield return CompletionPort.SingleOperation;
destination.EndWrite(machine.CompletionResult);
destination.Flush();
}
示例9: CopyTo
/// <summary>
/// Copies the contents between two <see cref="Stream"/> instances in an async fashion.
/// </summary>
/// <param name="source">The source stream to copy from.</param>
/// <param name="destination">The destination stream to copy to.</param>
/// <param name="onComplete">Delegate that should be invoked when the operation has completed. Will pass the source, destination and exception (if one was thrown) to the function. Can pass in <see langword="null" />.</param>
public static void CopyTo(this Stream source, Stream destination, Action<Stream, Stream, Exception> onComplete)
{
var buffer =
new byte[BufferSize];
Action<Exception> done = e =>
{
if (onComplete != null)
{
onComplete.Invoke(source, destination, e);
}
};
AsyncCallback rc = null;
rc = readResult =>
{
try
{
var read =
source.EndRead(readResult);
if (read <= 0)
{
done.Invoke(null);
return;
}
destination.BeginWrite(buffer, 0, read, writeResult =>
{
try
{
destination.EndWrite(writeResult);
source.BeginRead(buffer, 0, buffer.Length, rc, null);
}
catch (Exception ex)
{
done.Invoke(ex);
}
}, null);
}
catch (Exception ex)
{
done.Invoke(ex);
}
};
source.BeginRead(buffer, 0, buffer.Length, rc, null);
}
示例10: Start
public Task Start(Stream stream)
{
TaskCompletionSource<object> completed = new TaskCompletionSource<object>();
var bytes = encoding.GetBytes(text);
stream.BeginWrite(bytes, 0, bytes.Length,
async =>
{
try
{
stream.EndWrite(async);
completed.TrySetResult(null);
}
catch (Exception ex)
{
completed.TrySetException(ex);
}
},
null);
return completed.Task;
}
示例11: CopyStream
private static IEnumerator<Int32> CopyStream(AsyncEnumerator<Int64> ae, Stream source, Stream destination, Int32 bufferSize, Action<Int64> reportProgress) {
Byte[] buffer = new Byte[bufferSize];
Int64 totalBytesRead = 0;
while (true) {
ae.SetOperationTag("Reading from source stream");
// Read whichever is smaller (number of bytes left to read OR the buffer size)
source.BeginRead(buffer, 0, buffer.Length, ae.End(), null);
yield return 1;
Int32 bytesReadThisTime = source.EndRead(ae.DequeueAsyncResult());
totalBytesRead += bytesReadThisTime;
ae.SetOperationTag("Writing to destination stream");
destination.BeginWrite(buffer, 0, bytesReadThisTime, ae.End(), null);
yield return 1;
destination.EndWrite(ae.DequeueAsyncResult());
if (reportProgress != null) reportProgress(totalBytesRead);
if (bytesReadThisTime < buffer.Length) break;
}
ae.Result = totalBytesRead;
}
示例12: CopyTo
public static void CopyTo(this Stream source, Stream destination, int bufferSize)
{
long ts = DateTime.Now.Ticks;
long cbTotal = 0L;
byte[] read_buffer = new byte[bufferSize];
int cb = source.Read(read_buffer, 0, read_buffer.Length);
AutoResetEvent writeLock = new AutoResetEvent(false);
while (cb > 0)
{
cbTotal += cb;
try
{
byte[] write_buffer = read_buffer;
destination.BeginWrite(write_buffer, 0, cb, (AsyncCallback)delegate(IAsyncResult ar)
{
try
{
destination.EndWrite(ar);
}
finally
{
writeLock.Set();
}
}, null);
}
catch
{
writeLock.Set();
throw;
}
read_buffer = new byte[bufferSize];
cb = source.Read(read_buffer, 0, read_buffer.Length);
writeLock.WaitOne();
}
ts = DateTime.Now.Ticks - ts;
}
示例13: CopyTo
public static void CopyTo(this Stream input, Stream output, int buffer_size)
{
if (!input.CanRead)
throw new InvalidOperationException("input must be open for reading");
if (!output.CanWrite)
throw new InvalidOperationException("output must be open for writing");
byte[][] buffer = { new byte[buffer_size], new byte[buffer_size] };
int[] length = { 0, 0 };
int index = 0;
IAsyncResult read = input.BeginRead(buffer[index], 0, buffer[index].Length, null, null);
IAsyncResult write = null;
while (true)
{
// wait for the read operation to complete
read.AsyncWaitHandle.WaitOne();
length[index] = input.EndRead(read);
// if zero bytes read, the copy is complete
if (length[index] == 0)
break;
// wait for the in-flight write operation, if one exists, to complete
// the only time one won't exist is after the very first read operation completes
if (write != null)
{
write.AsyncWaitHandle.WaitOne();
output.EndWrite(write);
}
// start the new write operation
write = output.BeginWrite(buffer[index], 0, length[index], null, null);
// toggle the current, in-use buffer
// and start the read operation on the new buffer.
//
// Changed to use XOR to toggle between 0 and 1.
// A little speedier than using a ternary expression.
index ^= 1; // bufno = ( bufno == 0 ? 1 : 0 ) ;
read = input.BeginRead(buffer[index], 0, buffer[index].Length, null, null);
}
// wait for the final in-flight write operation, if one exists, to complete
// the only time one won't exist is if the input stream is empty.
if (write != null)
{
write.AsyncWaitHandle.WaitOne();
output.EndWrite(write);
}
output.Flush();
// return to the caller ;
return;
}
示例14: StreamWriteAsync
public static void StreamWriteAsync(
Stream stream,
byte[] buffer,
int offset,
int count,
SynchronizationContextWrapper syncContext,
Action<int, Exception> callback)
{
Exception error = null;
int length = 0;
try
{
stream.BeginWrite(buffer, offset, count,
delegate(IAsyncResult ar)
{
try
{
stream.EndWrite(ar);
stream.Flush();
length = count;
}
catch (Exception e)
{
error = e;
}
callback(length, error);
},
null);
}
catch (Exception e)
{
error = e;
callback(length, error);
}
}
示例15: Write
static void Write(Cargo<ArraySegment<byte>> cargo, Stream stream)
{
if (!cargo.Delayable) {
stream.Write(cargo.Result.Array, cargo.Result.Offset, cargo.Result.Count);
return;
}
var result = stream.BeginWrite(cargo.Result.Array, cargo.Result.Offset, cargo.Result.Count, asyncResult => {
if (asyncResult.CompletedSynchronously)
return;
stream.EndWrite(asyncResult);
cargo.Resume();
}, null);
if (result.CompletedSynchronously)
stream.EndWrite(result);
else
cargo.Delay();
}