本文整理汇总了C#中LazyAsyncResult类的典型用法代码示例。如果您正苦于以下问题:C# LazyAsyncResult类的具体用法?C# LazyAsyncResult怎么用?C# LazyAsyncResult使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
LazyAsyncResult类属于命名空间,在下文中一共展示了LazyAsyncResult类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: BeginWrite
internal IAsyncResult BeginWrite(BufferOffsetSize[] buffers, AsyncCallback asyncCallback, object asyncState)
{
LazyAsyncResult userAsyncResult = new LazyAsyncResult(this, asyncState, asyncCallback);
SplitWriteAsyncProtocolRequest asyncRequest = new SplitWriteAsyncProtocolRequest(userAsyncResult);
this.ProcessWrite(buffers, asyncRequest);
return userAsyncResult;
}
示例2: BeginAuthenticateAsClient
public virtual IAsyncResult BeginAuthenticateAsClient(string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
{
this._SslState.ValidateCreateContext(false, targetHost, enabledSslProtocols, null, clientCertificates, true, checkCertificateRevocation);
LazyAsyncResult lazyResult = new LazyAsyncResult(this._SslState, asyncState, asyncCallback);
this._SslState.ProcessAuthentication(lazyResult);
return lazyResult;
}
示例3: CheckCompletionBeforeNextReceive
private void CheckCompletionBeforeNextReceive(LazyAsyncResult lazyResult)
{
if (this.HandshakeComplete && this._RemoteOk)
{
if (lazyResult != null)
{
lazyResult.InvokeCallback();
}
}
else
{
this.StartReceiveBlob(lazyResult);
}
}
示例4: CheckCompletionBeforeNextSend
private void CheckCompletionBeforeNextSend(byte[] message, LazyAsyncResult lazyResult)
{
if (this.HandshakeComplete)
{
if (!this._RemoteOk)
{
throw new AuthenticationException(SR.GetString("net_io_header_id", new object[] { "MessageId", this._Framer.ReadHeader.MessageId, 20 }), null);
}
if (lazyResult != null)
{
lazyResult.InvokeCallback();
}
}
else
{
this.StartSendBlob(message, lazyResult);
}
}
示例5: SetResponse
//
// Process an exception and optionally set request for retrying
//
private void SetResponse(Exception E) {
#if DEBUG
bool callbackInvoked = false;
try
{
#endif
GlobalLog.Enter("HttpWebRequest#" + ValidationHelper.HashString(this) + "::SetResponse", E.ToString() + "/*** SETRESPONSE IN ERROR ***");
GlobalLog.ThreadContract(ThreadKinds.Unknown, "HttpWebRequest#" + ValidationHelper.HashString(this) + "::SetResponse");
HttpProcessingResult httpResult = HttpProcessingResult.Continue;
//
// Preserve the very first web exception occured if it was fatal
//
WebException webException = HaveResponse ? _ReadAResult.Result as WebException : null;
WebException newWebException = E as WebException;
if (webException != null && (webException.InternalStatus == WebExceptionInternalStatus.RequestFatal ||
webException.InternalStatus == WebExceptionInternalStatus.ServicePointFatal) &&
(newWebException == null || newWebException.InternalStatus != WebExceptionInternalStatus.RequestFatal))
{
E = webException;
}
else
{
webException = newWebException;
}
if (E != null)
{
if (Logging.On) Logging.Exception(Logging.Web, this, "", webException);
}
try {
if ( webException != null &&
(webException.InternalStatus == WebExceptionInternalStatus.Isolated ||
webException.InternalStatus == WebExceptionInternalStatus.ServicePointFatal ||
(webException.InternalStatus == WebExceptionInternalStatus.Recoverable && !m_OnceFailed)))
{
if (webException.InternalStatus == WebExceptionInternalStatus.Recoverable)
m_OnceFailed = true;
Pipelined = false;
if (_SubmitWriteStream != null && _OldSubmitWriteStream == null && _SubmitWriteStream.BufferOnly) {
_OldSubmitWriteStream = _SubmitWriteStream;
}
httpResult = DoSubmitRequestProcessing(ref E);
}
}
catch (Exception unexpectedException)
{
if (NclUtilities.IsFatal(unexpectedException)) throw;
// This is highly unexpected but if happens would result into Aborted exception with caught one as an inner exception
httpResult = HttpProcessingResult.Continue;
E = new WebException(NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled), unexpectedException, WebExceptionStatus.RequestCanceled, _HttpResponse);
}
finally
{
if (httpResult == HttpProcessingResult.Continue)
{
CancelTimer();
if (!(E is WebException) && !(E is SecurityException))
{
if (_HttpResponse==null) {
E = new WebException(E.Message, E);
}
else {
E = new WebException(
SR.GetString(
SR.net_servererror,
NetRes.GetWebStatusCodeString(
ResponseStatusCode,
_HttpResponse.StatusDescription)),
E,
WebExceptionStatus.ProtocolError,
_HttpResponse );
}
}
LazyAsyncResult writeAResult;
LazyAsyncResult readAResult = null;
// Async Abort may happen at any time including when the request is being cleared
// and resubmitted hence using checked response.
HttpWebResponse chkResponse = _HttpResponse;
lock (this)
{
writeAResult = _WriteAResult;
if (_ReadAResult == null)
{
_ReadAResult = new LazyAsyncResult(null, null, null, E); //never throws
//.........这里部分代码省略.........
示例6: ProcessResponse
/*++
Routine Description:
Wakes up blocked threads, so they can read response object,
from the result
We also handle the continuation/termination of a BeginGetResponse,
by saving out the result and calling its callback if needed.
--*/
private void ProcessResponse() {
GlobalLog.Enter("HttpWebRequest#" + ValidationHelper.HashString(this) + "::ProcessResponse", "From Cache = " + _HttpResponse.IsFromCache);
GlobalLog.ThreadContract(ThreadKinds.Unknown, "HttpWebRequest#" + ValidationHelper.HashString(this) + "::ProcessResponse");
HttpProcessingResult httpResult = HttpProcessingResult.Continue;
Exception exception = null;
// handle redirects, authentication, and such
httpResult = DoSubmitRequestProcessing(ref exception);
if (httpResult == HttpProcessingResult.Continue)
{
CancelTimer();
object result = exception != null ? (object) exception : (object) _HttpResponse;
if (_ReadAResult == null)
{
lock (this)
{
if (_ReadAResult == null)
{
_ReadAResult = new LazyAsyncResult(null, null, null); //never throws
}
}
}
try
{
FinishRequest(_HttpResponse, exception); // never throws
_ReadAResult.InvokeCallback(result);
try
{
SetRequestContinue();
}
catch { }
}
catch (Exception e)
{
Abort(e, AbortState.Public);
throw;
}
finally
{
// If request was already aborted the response will not be set on asyncResult, hence abort it now
if (exception == null && _ReadAResult.Result != (object) _HttpResponse)
{
WebException webException = _ReadAResult.Result as WebException;
if (webException != null && webException.Response != null)
{
GlobalLog.Assert(object.ReferenceEquals(webException.Response, _HttpResponse), "HttpWebRequset#{0}::ProcessResponse|Different HttpWebResponse in exception versus _HttpResponse.", ValidationHelper.HashString(this));
_HttpResponse.Abort(); // never throws
}
}
}
}
GlobalLog.Leave("HttpWebRequest#" + ValidationHelper.HashString(this) + "::ProcessResponse");
}
示例7: GetResponse
/// <devdoc>
/// <para>
/// Returns a response from a request to an Internet resource.
/// The response property. This property returns the WebResponse for this
/// request. This may require that a request be submitted first.
///
/// The idea is that we look and see if a request has already been
/// submitted. If one has, we'll just return the existing response
/// (if it's not null). If we haven't submitted a request yet, we'll
/// do so now, possible multiple times while we handle redirects
/// etc.
/// </para>
/// </devdoc>
public override WebResponse GetResponse() {
#if DEBUG
using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) {
#endif
GlobalLog.Enter("HttpWebRequest#" + ValidationHelper.HashString(this) + "::GetResponse");
if(Logging.On)Logging.Enter(Logging.Web, this, "GetResponse", "");
// No need to recheck the request parameters if we already did it in GetRequestStream().
// This prevents problems when redirects change verbs.
if (!RequestSubmitted)
{
CheckProtocol(false);
}
// Many of these logics require GetResponse() to be called after all write-stream activity is done. You can't call it
// simultaneously on another thread and expect it to block until it can run. Doing that can cause the request to
// hang.
ConnectStream stream = _OldSubmitWriteStream != null ? _OldSubmitWriteStream : _SubmitWriteStream;
// Close the request stream if the user forgot to do so. Throw an exception if user has not written all of
// the promised data.
if (stream != null && !stream.IsClosed)
{
if (stream.BytesLeftToWrite > 0)
{
throw new ProtocolViolationException(SR.GetString(SR.net_entire_body_not_written));
}
else
{
stream.Close();
}
}
else if (stream == null && HasEntityBody)
{
throw new ProtocolViolationException(SR.GetString(SR.net_must_provide_request_body));
}
// return response, if the response is already set
bool gotResponse = false;
HttpWebResponse httpWebResponse = null;
bool requestSubmitted;
lock (this)
{
requestSubmitted = SetRequestSubmitted();
if (HaveResponse)
{
gotResponse = true;
httpWebResponse = _ReadAResult.Result as HttpWebResponse;
}
else
{
if (_ReadAResult != null)
{
throw new InvalidOperationException(SR.GetString(SR.net_repcall));
}
Async = false;
// Since we don't really allow switching between [....] and async, if the request is already async, this needs to
// capture context for use in the ongoing async operations as if it were BeginGetResponse().
if (Async)
{
#if !FEATURE_PAL
ContextAwareResult readResult = new ContextAwareResult(IdentityRequired, true, this, null, null);
#else
ContextAwareResult readResult = new ContextAwareResult(false, true, this, null, null);
#endif
readResult.StartPostingAsyncOp(false);
readResult.FinishPostingAsyncOp();
_ReadAResult = readResult;
}
else
{
_ReadAResult = new LazyAsyncResult(this, null, null);
}
}
}
// See if we need to do the call-done processing here.
CheckDeferredCallDone(stream);
if (!gotResponse)
{
//The previous call may have been async. If we are now doing a [....] call, we should
//use the timeout
if (_Timer == null){
//.........这里部分代码省略.........
示例8: BeginReadOrWrite
IAsyncResult BeginReadOrWrite (ref AsyncProtocolRequest nestedRequest, ref BufferOffsetSize2 internalBuffer, AsyncOperation operation, BufferOffsetSize userBuffer, AsyncCallback asyncCallback, object asyncState)
{
LazyAsyncResult lazyResult = new LazyAsyncResult (this, asyncState, asyncCallback);
ProcessReadOrWrite (ref nestedRequest, ref internalBuffer, operation, userBuffer, lazyResult);
return lazyResult;
}
示例9: InternalWrite
//
// Handles either async or sync Writing for *public* stream API
//
private IAsyncResult InternalWrite(bool async, byte[] buffer, int offset, int size, AsyncCallback callback, object state ) {
//
// if we have a stream error, or we've already shut down this socket
// then we must prevent new BeginRead/BeginWrite's from getting
// submited to the socket, since we've already closed the stream.
//
if (ErrorInStream) {
GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::InternalWrite() throwing:" + m_ErrorException.ToString());
throw m_ErrorException;
}
if (IsClosed && !IgnoreSocketErrors) {
GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::InternalWrite() throwing");
throw new WebException(
NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.ConnectionClosed),
WebExceptionStatus.ConnectionClosed);
}
if (m_Request.Aborted && !IgnoreSocketErrors) {
GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::InternalWrite() throwing");
throw new WebException(
NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled),
WebExceptionStatus.RequestCanceled);
}
int nesting = Interlocked.CompareExchange(ref m_CallNesting, Nesting.IoInProgress, Nesting.Idle);
GlobalLog.Print((async?"Async ":"") + "InternalWrite() In: callNesting : " + nesting.ToString());
if (nesting != Nesting.Idle && nesting != Nesting.Closed)
{
throw new NotSupportedException(SR.GetString(SR.net_no_concurrent_io_allowed));
}
//
// buffer data to the ScatterGatherBuffers
// regardles of chunking, we buffer the data as if we were not chunking
// and on resubmit, we don't bother chunking.
//
if (BufferedData!=null && size != 0 && (m_Request.ContentLength != 0 || !IsPostStream || !m_Request.NtlmKeepAlive)) {
//
// if we don't need to, we shouldn't send data on the wire as well
// but in this case we gave a stream to the user so we have transport
//
BufferedData.Write(buffer, offset, size);
}
LazyAsyncResult asyncResult = null;
bool completeSync = false;
try
{
if (size == 0 || BufferOnly || m_SuppressWrite || IgnoreSocketErrors)
{
//
// We're not putting this data on the wire, then we're done
//
if(m_SuppressWrite && m_BytesLeftToWrite > 0 && size > 0)
{
m_BytesLeftToWrite -= size;
}
GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::InternalWrite() ----ing: size==0 || BufferOnly || IgnoreSocketErrors= " + (size==0) + BufferOnly + IgnoreSocketErrors);
if (async) {
asyncResult = new LazyAsyncResult(this, state, callback);
completeSync = true;
}
return asyncResult;
}
else if (WriteChunked) {
//
// We're chunking. Write the chunk header out first,
// then the data, then a CRLF.
// for this we'll use BeginMultipleSend();
//
int chunkHeaderOffset = 0;
byte[] chunkHeaderBuffer = GetChunkHeader(size, out chunkHeaderOffset);
BufferOffsetSize[] buffers;
GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::InternalWrite() m_ErrorResponseStatus:" + m_ErrorResponseStatus);
if (m_ErrorResponseStatus) {
//if we already got a (>200) response, then just terminate chunking and
//switch to simple buffering (if any)
GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::InternalWrite() setting m_IgnoreSocketErrors to True (was:" + m_IgnoreSocketErrors + ") sending chunk terminator");
m_IgnoreSocketErrors = true;
buffers = new BufferOffsetSize[1];
buffers[0] = new BufferOffsetSize(NclConstants.ChunkTerminator, 0, NclConstants.ChunkTerminator.Length, false);
}
else {
buffers = new BufferOffsetSize[3];
buffers[0] = new BufferOffsetSize(chunkHeaderBuffer, chunkHeaderOffset, chunkHeaderBuffer.Length - chunkHeaderOffset, false);
buffers[1] = new BufferOffsetSize(buffer, offset, size, false);
buffers[2] = new BufferOffsetSize(NclConstants.CRLF, 0, NclConstants.CRLF.Length, false);
}
asyncResult = (async) ? new NestedMultipleAsyncResult(this, state, callback, buffers) : null;
//
// after setting up the buffers and error checking do the async Write Call
//.........这里部分代码省略.........
示例10: BeginSend
internal virtual IAsyncResult BeginSend(BaseWriter writer, bool sendEnvelope, bool allowUnicode,
AsyncCallback callback, object state)
{
PrepareHeaders(sendEnvelope, allowUnicode);
writer.WriteHeaders(Headers, allowUnicode);
if (Content != null)
{
return Content.BeginSend(writer, callback, allowUnicode, state);
}
else
{
LazyAsyncResult result = new LazyAsyncResult(this, state, callback);
IAsyncResult newResult = writer.BeginGetContentStream(EmptySendCallback, new EmptySendContext(writer, result));
if (newResult.CompletedSynchronously)
{
writer.EndGetContentStream(newResult).Close();
}
return result;
}
}
示例11: ProcessAuthentication
internal bool ProcessAuthentication(LazyAsyncResult result)
{
bool doHandshake = false;
bool isSyncCall = result == null;
lock (m_PendingIO)
{
// do we have handshake as already done before we grabbed a lock?
if (m_Worker.IsAuthenticated)
return false;
if (m_PendingIO.Count == 0)
{
doHandshake = true;
}
if (isSyncCall)
{
// we will wait on this guy in this method for the handshake to complete
result = new LazyAsyncResult(this, null, null);
}
m_PendingIO.Add(result);
}
try {
if (doHandshake)
{
bool success = true;
LazyAsyncResult handshakeResult = null;
try
{
m_Worker.ValidateCreateContext(false,
m_DestinationHost,
(System.Security.Authentication.SslProtocols)ServicePointManager.SecurityProtocol,
null, m_ClientCertificates,
true,
ServicePointManager.CheckCertificateRevocationList,
ServicePointManager.CheckCertificateName);
if (!isSyncCall)
{
// wrap a user async IO/Handshake request into auth request
handshakeResult = new LazyAsyncResult(m_Worker, null, new AsyncCallback(WakeupPendingIO));
#if DEBUG
result._DebugAsyncChain = handshakeResult;
#endif
}
//
// TlsStream is used by classes that manually control ExecutionContext, so set it here if we need to.
//
if (_ExecutionContext != null)
{
ExecutionContext.Run(_ExecutionContext.CreateCopy(), new ContextCallback(CallProcessAuthentication), handshakeResult);
}
else
{
m_Worker.ProcessAuthentication(handshakeResult);
}
}
catch
{
success = false;
throw;
}
finally
{
if (isSyncCall || !success)
{
lock (m_PendingIO)
{
if(m_PendingIO.Count > 1)
{
// It was a real [....] handshake (now completed) and another IO came in.
// It's now waiting on us so resume.
ThreadPool.QueueUserWorkItem(new WaitCallback(StartWakeupPendingIO), null);
}
else {
m_PendingIO.Clear();
}
}
}
}
}
else if (isSyncCall)
{
GlobalLog.Assert(result != null, "TlsStream::ProcessAuthentication() this is a [....] call and it did not started the handshake hence null result must be wrapped into LazyAsyncResult");
Exception e = result.InternalWaitForCompletion() as Exception;
if (e != null)
throw e;
}
}
catch {
if (m_Worker.IsCertValidationFailed) {
m_ExceptionStatus = WebExceptionStatus.TrustFailure;
}
else if (m_Worker.LastSecurityStatus != SecurityStatus.OK) {
m_ExceptionStatus = WebExceptionStatus.SecureChannelFailure;
//.........这里部分代码省略.........
示例12: MimePartContext
internal MimePartContext(BaseWriter writer, LazyAsyncResult result, IEnumerator<MimeBasePart> partsEnumerator) {
this.writer = writer;
this.result = result;
this.partsEnumerator = partsEnumerator;
}
示例13: BeginAuthenticateAsServer
public IAsyncResult BeginAuthenticateAsServer (X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
{
ValidateCreateContext (true, string.Empty, enabledSslProtocols, serverCertificate, null, clientCertificateRequired);
var result = new LazyAsyncResult (this, asyncState, asyncCallback);
ProcessAuthentication (result);
return result;
}
示例14: MimePartContext
internal MimePartContext(BaseWriter writer, LazyAsyncResult result)
{
this.writer = writer;
this.result = result;
buffer = new byte[maxBufferSize];
}
示例15: ProcessReadOrWrite
int ProcessReadOrWrite (ref AsyncProtocolRequest nestedRequest, ref BufferOffsetSize2 internalBuffer, AsyncOperation operation, BufferOffsetSize userBuffer, LazyAsyncResult lazyResult)
{
if (userBuffer == null || userBuffer.Buffer == null)
throw new ArgumentNullException ("buffer");
if (userBuffer.Offset < 0)
throw new ArgumentOutOfRangeException ("offset");
if (userBuffer.Size < 0 || userBuffer.Offset + userBuffer.Size > userBuffer.Buffer.Length)
throw new ArgumentOutOfRangeException ("count");
CheckThrow (true);
var name = internalBuffer == readBuffer ? "read" : "write";
Debug ("ProcessReadOrWrite: {0} {1}", name, userBuffer);
var asyncRequest = new AsyncProtocolRequest (this, lazyResult, userBuffer);
return StartOperation (ref nestedRequest, ref internalBuffer, operation, asyncRequest, name);
}