本文整理汇总了C#中System.IO.Stream.EndRead方法的典型用法代码示例。如果您正苦于以下问题:C# Stream.EndRead方法的具体用法?C# Stream.EndRead怎么用?C# Stream.EndRead使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.Stream
的用法示例。
在下文中一共展示了Stream.EndRead方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: StreamReadAsync
public static void StreamReadAsync(
Stream stream,
byte[] buffer,
int offset,
int count,
SynchronizationContextWrapper syncContext,
Action<int, Exception> callback)
{
Exception error = null;
int length = 0;
try
{
stream.BeginRead(buffer, offset, count,
delegate(IAsyncResult ar)
{
try
{
length = stream.EndRead(ar);
}
catch (Exception e)
{
error = e;
}
callback(length, error);
},
null);
}
catch (Exception e)
{
error = e;
callback(length, error);
}
}
示例2: 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;
}
示例3: ReadDataFromStream
private static string ReadDataFromStream(Stream str)
{
var buff = new byte[10000];
var asyncResult = str.BeginRead(buff, 0, buff.Length, null, null);
var bytesRead = str.EndRead(asyncResult);
return Encoding.UTF8.GetString(buff, 0, bytesRead);
}
示例4: OnEnter
private IAsyncResult OnEnter(Object sender, EventArgs e, AsyncCallback cb, Object state) {
Debug.Assert(_inputStream == null);
_app = (HttpApplication)sender;
HttpContext context = _app.Context;
HttpRequest request = context.Request;
HttpWorkerRequest wr = context.WorkerRequest;
HttpAsyncResult httpAsyncResult = new HttpAsyncResult(cb, state);
AsyncPreloadModeFlags asyncPreloadMode = context.AsyncPreloadMode;
int contentLength;
bool isForm = false;
bool isFormMultiPart = false;
if (asyncPreloadMode == AsyncPreloadModeFlags.None
|| request.ReadEntityBodyMode != ReadEntityBodyMode.None
|| wr == null
|| !wr.SupportsAsyncRead
|| !wr.HasEntityBody()
|| wr.IsEntireEntityBodyIsPreloaded()
|| context.Handler == null
|| context.Handler is TransferRequestHandler
|| context.Handler is DefaultHttpHandler
|| (contentLength = request.ContentLength) > RuntimeConfig.GetConfig(context).HttpRuntime.MaxRequestLengthBytes
|| ((isForm = StringUtil.StringStartsWithIgnoreCase(request.ContentType, "application/x-www-form-urlencoded"))
&& (asyncPreloadMode & AsyncPreloadModeFlags.Form) != AsyncPreloadModeFlags.Form)
|| ((isFormMultiPart = StringUtil.StringStartsWithIgnoreCase(request.ContentType, "multipart/form-data"))
&& (asyncPreloadMode & AsyncPreloadModeFlags.FormMultiPart) != AsyncPreloadModeFlags.FormMultiPart)
|| !isForm && !isFormMultiPart && (asyncPreloadMode & AsyncPreloadModeFlags.NonForm) != AsyncPreloadModeFlags.NonForm
) {
Debug.Trace("AsyncPreload", " *** AsyncPreload skipped *** ");
httpAsyncResult.Complete(true, null, null);
return httpAsyncResult;
}
Debug.Trace("AsyncPreload", " *** AsyncPreload started *** ");
try {
if (_callback == null) {
_callback = new AsyncCallback(OnAsyncCompletion);
}
_inputStream = request.GetBufferedInputStream();
byte[] buffer = _app.EntityBuffer;
int bytesRead = 0;
// loop to prevent recursive calls and potential stack overflow if/when it completes synchronously
do {
IAsyncResult readAsyncResult = _inputStream.BeginRead(buffer, 0, buffer.Length, _callback, httpAsyncResult);
if (!readAsyncResult.CompletedSynchronously) {
return httpAsyncResult;
}
bytesRead = _inputStream.EndRead(readAsyncResult);
} while (bytesRead != 0);
}
catch {
Reset();
throw;
}
httpAsyncResult.Complete(true, null, null);
return httpAsyncResult;
}
示例5: ReadTask
private static Task<int> ReadTask(Stream stream, byte[] buffer, int offset, int count, object state)
{
var tcs = new TaskCompletionSource<int>();
stream.BeginRead(buffer, offset, count, ar =>
{
try { tcs.SetResult(stream.EndRead(ar)); }
catch (Exception exc) { tcs.SetException(exc); }
}, state);
return tcs.Task;
}
示例6: ReadStream
public static int ReadStream(Stream stream, byte[] buffer, int offset, int count, int timeout)
{
if (stream == null || buffer == null || buffer.Length < (offset + count))
return -1;
IAsyncResult arRead = stream.BeginRead(buffer, offset, count, null, null);
if (!arRead.AsyncWaitHandle.WaitOne(timeout))
{
throw new TimeoutException("Could not read within the timeout period.");
}
return stream.EndRead(arRead);
}
示例7: EndRead
private static int EndRead(Stream stream, IAsyncResult ar, byte[] buffer)
{
try
{
return stream.EndRead(ar);
}
catch (Exception)
{
return stream.ReadAsync(buffer).Result;
}
}
示例8: ReadUnsignedVarint
private static void ReadUnsignedVarint(
Stream stream,
Bcp.ReadState readState,
ProcessReadVarint processReadVarint,
BcpDelegate.ExceptionHandler exceptionHandler)
{
var buffer = new byte[1];
var i = 0;
uint result = 0U;
AsyncCallback asyncCallback = null;
asyncCallback = asyncResult =>
{
try
{
int numBytesRead = stream.EndRead(asyncResult);
if (numBytesRead != 1)
{
exceptionHandler(new EndOfStreamException());
}
uint b = buffer[0];
if (i < 32)
{
if (b >= 0x80)
{
result |= ((b & 0x7f) << i);
i += 7;
stream.BeginRead(buffer, 0, 1, asyncCallback, readState);
}
else
{
result |= (b << i);
processReadVarint(result);
}
}
else
{
exceptionHandler(new BcpException.VarintTooBig());
}
}
catch (Exception e)
{
exceptionHandler(e);
}
};
try
{
stream.BeginRead(buffer, 0, 1, asyncCallback, readState);
}
catch (Exception e)
{
exceptionHandler(e);
}
}
示例9: Connect
public bool Connect()
{
try
{
//_socket.Connect(host, port);
var connect_result = _socket.BeginConnect(host, port, null, null);
if(!connect_result.AsyncWaitHandle.WaitOne(1500))
{
throw new Exception();
}
_socket.EndConnect(connect_result);
}
catch
{
this.Destruct("Failed to connect.", true);
return false;
}
_stream = _socket.GetStream();
isConnected = true;
Program._RconBox.SomethingToSend.Enabled = true;
byte[] buff = new byte[1];
AsyncCallback callback = null;
callback = ar =>
{
try
{
int bytes = _stream.EndRead(ar);
//Program._RconBox.OutputBox.Text += buff;
Program.wattosend.Add(buff[0]);
buff[0] = 0;
if (!this.isConnected || bytes == 0)
{
this.Destruct("Disconnected!");
return;
}
_stream.BeginRead(buff, 0, 1, callback, null);
}
catch
{
this.Destruct("Reading has failed");
}
};
_stream.BeginRead(buff, 0, 1, callback, null);
this.Send("set redrawcmd false");
this.Send("login " + this.pass);
return true;
}
示例10: StreamCopy
private static AsyncEvent StreamCopy(Stream src, Stream dst, Func<bool> assertContinuation, Action onException = null, Action<int> onProgress = null)
{
var evt = new AsyncEvent(false, false);
var exception = false;
AsyncCallback cb = null;
cb = (ar) =>
{
var count = src.EndRead(ar);
var readed = (byte[])ar.AsyncState;
if (exception) return;
if (count != 0)
{
lock (evt)
{
if (exception) return;
var newArray = new byte[BLOCK_SIZE];
if (!assertContinuation())
return;
if (onProgress != null)
onProgress(count);
src.BeginRead(newArray, 0, BLOCK_SIZE, cb, newArray);
try
{
dst.Write(readed, 0, count);
}
catch (Exception e)
{
exception = true;
if(onException != null)
onException();
}
}
}
else
{
lock (evt)
{
src.Close();
evt.Set();
}
}
};
var startBuffer = new byte[BLOCK_SIZE];
src.BeginRead(startBuffer, 0, BLOCK_SIZE, cb, startBuffer);
return evt;
}
示例11: StreamContainsSeqeunce
public bool StreamContainsSeqeunce(Stream contentStream)
{
int num;
if (contentStream == null)
{
throw new ArgumentNullException("contentStream");
}
if (this.FSequence == null)
{
throw new ArgumentNullException("sequence");
}
if (this.FSequence.Length == 0)
{
return false;
}
byte[] buffer = new byte[0x40000];
byte[] buffer2 = new byte[0x40000];
byte[] buffer3 = buffer;
byte[] buffer4 = buffer2;
int offset = 0;
bool flag = false;
IAsyncResult asyncResult = contentStream.BeginRead(buffer3, 0, buffer3.Length, null, null);
do
{
if (!base.OnProgress(0))
{
break;
}
num = contentStream.EndRead(asyncResult);
if (num > 0)
{
buffer3 = Interlocked.Exchange<byte[]>(ref buffer4, buffer3);
int num3 = offset;
offset = Math.Min(this.FSequence.Length - 1, num);
asyncResult = contentStream.BeginRead(buffer3, offset, buffer3.Length - offset, null, null);
flag = ByteArrayHelper.IndexOf(this.FSequence, buffer4, buffer4.Length) >= 0;
Array.Copy(buffer4, (num + num3) - offset, buffer3, 0, offset);
}
else
{
asyncResult = null;
}
}
while ((num > 0) && !flag);
if (asyncResult != null)
{
contentStream.EndRead(asyncResult);
}
return flag;
}
示例12: EndReadFrom
/// <summary>
/// Ends reading from stream
/// </summary>
/// <param name="stream">Stream to stop reading from</param>
/// <param name="ar">Result of reading</param>
/// <returns></returns>
public Int32 EndReadFrom(Stream stream, IAsyncResult ar)
{
if (_connection.State == IrcConnectionState.Opened)
{
var read = stream.EndRead(ar);
if (read > 0)
{
_count += read;
}
var str = IrcDefinition.Encoding.GetString(_buffer, 0, _count);
return read;
}
else
{
return 0;
}
}
示例13: FromStream
public static BodyAction FromStream(Stream stream)
{
return (next, error, complete) =>
{
var buffer = new byte[4096];
var continuation = new AsyncCallback[1];
bool[] stopped = {false};
continuation[0] = result =>
{
if (result != null && result.CompletedSynchronously) return;
try
{
for (;;)
{
if (result != null)
{
var count = stream.EndRead(result);
if (stopped[0]) return;
if (count <= 0)
{
complete();
return;
}
var data = new ArraySegment<byte>(buffer, 0, count);
if (next(data, () => continuation[0](null))) return;
}
if (stopped[0]) return;
result = stream.BeginRead(buffer, 0, buffer.Length, continuation[0], null);
if (!result.CompletedSynchronously) return;
}
}
catch (Exception ex)
{
error(ex);
}
};
continuation[0](null);
return () => { stopped[0] = true; };
};
}
示例14: 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;
}
示例15: ReadBytesAsync
public static IEnumerable<CompletionPort> ReadBytesAsync(AsyncMachine<byte[]> machine, Stream stream, int length)
{
var attributeHelper = new AttributeHelper<VhdHeader>();
var buffer = new byte[length];
int readCount = 0;
int remaining = length;
while (remaining > 0)
{
stream.BeginRead(buffer, readCount, remaining, machine.CompletionCallback, null);
yield return CompletionPort.SingleOperation;
var currentRead = stream.EndRead(machine.CompletionResult);
if (currentRead == 0)
{
break;
}
readCount += currentRead;
remaining -= currentRead;
}
machine.ParameterValue = buffer;
yield break;
}