本文整理汇总了C#中System.IO.Stream.BeginWrite方法的典型用法代码示例。如果您正苦于以下问题:C# Stream.BeginWrite方法的具体用法?C# Stream.BeginWrite怎么用?C# Stream.BeginWrite使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.Stream
的用法示例。
在下文中一共展示了Stream.BeginWrite方法的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: SerializeToStreamAsync
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
Contract.Assert(stream != null);
// Serialize header
byte[] header = SerializeHeader();
TaskCompletionSource<object> writeTask = new TaskCompletionSource<object>();
try
{
// We don't use TaskFactory.FromAsync as it generates an FxCop CA908 error
Tuple<HttpMessageContent, Stream, TaskCompletionSource<object>> state =
new Tuple<HttpMessageContent, Stream, TaskCompletionSource<object>>(this, stream, writeTask);
IAsyncResult result = stream.BeginWrite(header, 0, header.Length, _onWriteComplete, state);
if (result.CompletedSynchronously)
{
WriteComplete(result, this, stream, writeTask);
}
}
catch (Exception e)
{
writeTask.TrySetException(e);
}
return writeTask.Task;
}
示例3: 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;
}
示例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: 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;
}
示例6: 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();
}
示例7: 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);
}
示例8: 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;
}
示例9: 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;
}
示例10: 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;
}
示例11: CopyStream
static IEnumerable<Task> CopyStream(Stream input, Stream output)
{
var buffer = new byte[0x2000];
while (true)
{
// Create task to read from the input stream
var read = Task<int>.Factory.FromAsync((buf, offset, count, callback, state) =>
{
Console.WriteLine("Issuing BeginRead");
return input.BeginRead(buf, offset, count, callback, state);
},
ar =>
{
Console.WriteLine("Read completed");
return input.EndRead(ar);
},
buffer, 0, buffer.Length, null);
yield return read;
// If we read no data, return
if (read.Result == 0) break;
// Create task to write to the output stream
yield return Task.Factory.FromAsync((buf, offset, count, callback, state) =>
{
Console.WriteLine("Issuing BeginWrite");
return output.BeginWrite(buf, offset, count, callback, state);
},
ar =>
{
Console.WriteLine("Write completed");
output.EndWrite(ar);
}, buffer, 0, read.Result, null);
}
}
示例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: ProgressWriteAsyncResult
public ProgressWriteAsyncResult(Stream innerStream, ProgressStream progressStream, byte[] buffer, int offset, int count, AsyncCallback callback, object state)
: base(callback, state)
{
Contract.Assert(innerStream != null);
Contract.Assert(progressStream != null);
Contract.Assert(buffer != null);
_innerStream = innerStream;
_progressStream = progressStream;
_count = count;
try
{
IAsyncResult result = innerStream.BeginWrite(buffer, offset, count, _writeCompletedCallback, this);
if (result.CompletedSynchronously)
{
WriteCompleted(result);
}
}
catch (Exception e)
{
Complete(true, e);
}
}
示例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: WriteToStreamAsync
public Task WriteToStreamAsync(Stream stream)
{
return Task.Factory.FromAsync((Func<AsyncCallback, object, IAsyncResult>) ((callback, state) => stream.BeginWrite(this.buffer, 0, this.storedCount, callback, state)), new Action<IAsyncResult>(stream.EndWrite), null);
}