本文整理汇总了C#中System.Net.WebAsyncResult类的典型用法代码示例。如果您正苦于以下问题:C# WebAsyncResult类的具体用法?C# WebAsyncResult怎么用?C# WebAsyncResult使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
WebAsyncResult类属于System.Net命名空间,在下文中一共展示了WebAsyncResult类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Abort
public override void Abort ()
{
if (Interlocked.CompareExchange (ref aborted, 1, 0) == 1)
return;
if (haveResponse && finished_reading)
return;
haveResponse = true;
if (abortHandler != null) {
try {
abortHandler (this, EventArgs.Empty);
} catch (Exception) {}
abortHandler = null;
}
if (asyncWrite != null) {
WebAsyncResult r = asyncWrite;
if (!r.IsCompleted) {
try {
WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
r.SetCompleted (false, wexc);
r.DoCallback ();
} catch {}
}
asyncWrite = null;
}
if (asyncRead != null) {
WebAsyncResult r = asyncRead;
if (!r.IsCompleted) {
try {
WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
r.SetCompleted (false, wexc);
r.DoCallback ();
} catch {}
}
asyncRead = null;
}
if (writeStream != null) {
try {
writeStream.Close ();
writeStream = null;
} catch {}
}
if (webResponse != null) {
try {
webResponse.Close ();
webResponse = null;
} catch {}
}
}
示例2: SetWriteStreamCB
void SetWriteStreamCB (IAsyncResult ar)
{
WebAsyncResult result = ar as WebAsyncResult;
if (result.Exception != null) {
WebException wexc = result.Exception as WebException;
if (wexc != null) {
SetWriteStreamError (wexc.Status, wexc);
return;
}
SetWriteStreamError (WebExceptionStatus.SendFailure, result.Exception);
return;
}
haveRequest = true;
if (bodyBuffer != null) {
// The body has been written and buffered. The request "user"
// won't write it again, so we must do it.
if (auth_state.NtlmAuthState != NtlmAuthState.Challenge && proxy_auth_state.NtlmAuthState != NtlmAuthState.Challenge) {
// FIXME: this is a blocking call on the thread pool that could lead to thread pool exhaustion
writeStream.Write (bodyBuffer, 0, bodyBufferLength);
bodyBuffer = null;
writeStream.Close ();
}
} else if (method != "HEAD" && method != "GET" && method != "MKCOL" && method != "CONNECT" &&
method != "TRACE") {
if (getResponseCalled && !writeStream.RequestWritten)
// FIXME: this is a blocking call on the thread pool that could lead to thread pool exhaustion
writeStream.WriteRequest ();
}
if (asyncWrite != null) {
asyncWrite.SetCompleted (false, writeStream);
asyncWrite.DoCallback ();
asyncWrite = null;
}
}
示例3: BeginGetRequestStream
public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
{
if (Aborted)
throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD" ||
method == "TRACE");
if (method == null || !send)
throw new ProtocolViolationException ("Cannot send data when method is: " + method);
if (contentLength == -1 && !sendChunked && !allowBuffering && KeepAlive)
throw new ProtocolViolationException ("Content-Length not set");
string transferEncoding = TransferEncoding;
if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
throw new ProtocolViolationException ("SendChunked should be true.");
lock (locker)
{
if (getResponseCalled)
throw new InvalidOperationException ("The operation cannot be performed once the request has been submitted.");
if (asyncWrite != null) {
throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
"method while a previous call is still in progress.");
}
asyncWrite = new WebAsyncResult (this, callback, state);
initialMethod = method;
if (haveRequest) {
if (writeStream != null) {
asyncWrite.SetCompleted (true, writeStream);
asyncWrite.DoCallback ();
return asyncWrite;
}
}
gotRequestStream = true;
WebAsyncResult result = asyncWrite;
if (!requestSent) {
requestSent = true;
redirects = 0;
servicePoint = GetServicePoint ();
abortHandler = servicePoint.SendRequest (this, connectionGroup);
}
return result;
}
}
示例4: GetRequestStream
public override Stream GetRequestStream()
{
IAsyncResult asyncResult = asyncWrite;
if (asyncResult == null) {
asyncResult = BeginGetRequestStream (null, null);
asyncWrite = (WebAsyncResult) asyncResult;
}
if (!asyncResult.IsCompleted && !asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
Abort ();
throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
}
return EndGetRequestStream (asyncResult);
}
示例5: SetResponseError
internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
{
if (Aborted)
return;
lock (locker) {
string msg = String.Format ("Error getting response stream ({0}): {1}", where, status);
WebAsyncResult r = asyncRead;
if (r == null)
r = asyncWrite;
WebException wexc;
if (e is WebException) {
wexc = (WebException) e;
} else {
wexc = new WebException (msg, e, status, null);
}
if (r != null) {
if (!r.IsCompleted) {
r.SetCompleted (false, wexc);
r.DoCallback ();
} else if (r == asyncWrite) {
saved_exc = wexc;
}
haveResponse = true;
asyncRead = null;
asyncWrite = null;
} else {
haveResponse = true;
saved_exc = wexc;
}
}
}
示例6: SetResponseData
internal void SetResponseData (WebConnectionData data)
{
lock (locker) {
if (Aborted) {
if (data.stream != null)
data.stream.Close ();
return;
}
WebException wexc = null;
try {
webResponse = new HttpWebResponse (actualUri, method, data, cookieContainer);
} catch (Exception e) {
wexc = new WebException (e.Message, e, WebExceptionStatus.ProtocolError, null);
if (data.stream != null)
data.stream.Close ();
}
if (wexc == null && (method == "POST" || method == "PUT")) {
CheckSendError (data);
if (saved_exc != null)
wexc = (WebException) saved_exc;
}
WebAsyncResult r = asyncRead;
bool forced = false;
if (r == null && webResponse != null) {
// This is a forced completion (302, 204)...
forced = true;
r = new WebAsyncResult (null, null);
r.SetCompleted (false, webResponse);
}
if (r != null) {
if (wexc != null) {
haveResponse = true;
if (!r.IsCompleted)
r.SetCompleted (false, wexc);
r.DoCallback ();
return;
}
bool redirected;
try {
redirected = CheckFinalStatus (r);
if (!redirected) {
if (ntlm_auth_state != NtlmAuthState.None && authCompleted && webResponse != null
&& (int)webResponse.StatusCode < 400) {
WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
if (wce != null) {
WebConnection cnc = wce.Connection;
cnc.NtlmAuthenticated = true;
}
}
// clear internal buffer so that it does not
// hold possible big buffer (bug #397627)
if (writeStream != null)
writeStream.KillBuffer ();
haveResponse = true;
r.SetCompleted (false, webResponse);
r.DoCallback ();
} else {
if (webResponse != null) {
if (ntlm_auth_state != NtlmAuthState.None) {
HandleNtlmAuth (r);
return;
}
webResponse.Close ();
}
finished_reading = false;
haveResponse = false;
webResponse = null;
r.Reset ();
servicePoint = GetServicePoint ();
abortHandler = servicePoint.SendRequest (this, connectionGroup);
}
} catch (WebException wexc2) {
if (forced) {
saved_exc = wexc2;
haveResponse = true;
}
r.SetCompleted (false, wexc2);
r.DoCallback ();
return;
} catch (Exception ex) {
wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null);
if (forced) {
saved_exc = wexc;
haveResponse = true;
}
r.SetCompleted (false, wexc);
r.DoCallback ();
return;
}
}
}
}
示例7: Redirect
bool Redirect (WebAsyncResult result, HttpStatusCode code)
{
redirects++;
Exception e = null;
string uriString = null;
switch (code) {
case HttpStatusCode.Ambiguous: // 300
e = new WebException ("Ambiguous redirect.");
break;
case HttpStatusCode.MovedPermanently: // 301
case HttpStatusCode.Redirect: // 302
case HttpStatusCode.TemporaryRedirect: // 307
/* MS follows the redirect for POST too
if (method != "GET" && method != "HEAD") // 10.3
return false;
*/
contentLength = -1;
bodyBufferLength = 0;
bodyBuffer = null;
if (code != HttpStatusCode.TemporaryRedirect)
method = "GET";
uriString = webResponse.Headers ["Location"];
break;
case HttpStatusCode.SeeOther: //303
method = "GET";
uriString = webResponse.Headers ["Location"];
break;
case HttpStatusCode.NotModified: // 304
return false;
case HttpStatusCode.UseProxy: // 305
e = new NotImplementedException ("Proxy support not available.");
break;
case HttpStatusCode.Unused: // 306
default:
e = new ProtocolViolationException ("Invalid status code: " + (int) code);
break;
}
if (e != null)
throw e;
if (uriString == null)
throw new WebException ("No Location header found for " + (int) code,
WebExceptionStatus.ProtocolError);
Uri prev = actualUri;
try {
actualUri = new Uri (actualUri, uriString);
} catch (Exception) {
throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
uriString, (int) code),
WebExceptionStatus.ProtocolError);
}
hostChanged = (actualUri.Scheme != prev.Scheme || Host != prev.Authority);
return true;
}
示例8: WriteRequestAsync
internal WebAsyncResult WriteRequestAsync (AsyncCallback callback, object state)
{
if (requestWritten)
return null;
requestWritten = true;
if (sendChunked)
return null;
if (!allowBuffering || writeBuffer == null)
return null;
byte[] bytes = writeBuffer.GetBuffer ();
int length = (int)writeBuffer.Length;
if (request.ContentLength != -1 && request.ContentLength < length) {
nextReadCalled = true;
cnc.Close (true);
throw new WebException ("Specified Content-Length is less than the number of bytes to write", null,
WebExceptionStatus.ServerProtocolViolation, null);
}
var result = new WebAsyncResult (callback, state);
result.InnerAsyncResult = SetHeadersAsync (true, WriteRequestAsyncCB, result);
if (result.InnerAsyncResult == null)
WriteRequestAsyncCB (result);
return result;
}
示例9: BeginGetResponse
public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
{
if (Aborted)
throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
if (method == null)
throw new ProtocolViolationException ("Method is null.");
#if !NET_2_0
bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD" ||
method == "TRACE" || method == "DELETE");
if (send && contentLength < 0 && !sendChunked && !allowBuffering && KeepAlive)
throw new ProtocolViolationException ("Buffering is disabled, ContentLength is negative and SendChunked is disabled.");
if (!send && (contentLength > -1 || sendChunked))
throw new ProtocolViolationException ("ContentLength can't be set for non-write operations.");
#endif
string transferEncoding = TransferEncoding;
if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
throw new ProtocolViolationException ("SendChunked should be true.");
Monitor.Enter (locker);
getResponseCalled = true;
if (asyncRead != null && !haveResponse) {
Monitor.Exit (locker);
throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
"method while a previous call is still in progress.");
}
CheckIfForceWrite ();
asyncRead = new WebAsyncResult (this, callback, state);
WebAsyncResult aread = asyncRead;
initialMethod = method;
if (haveResponse) {
Exception saved = saved_exc;
if (webResponse != null) {
Monitor.Exit (locker);
if (saved == null) {
aread.SetCompleted (true, webResponse);
} else {
aread.SetCompleted (true, saved);
}
aread.DoCallback ();
return aread;
} else if (saved != null) {
Monitor.Exit (locker);
aread.SetCompleted (true, saved);
aread.DoCallback ();
return aread;
}
}
if (!requestSent) {
requestSent = true;
redirects = 0;
servicePoint = GetServicePoint ();
abortHandler = servicePoint.SendRequest (this, connectionGroup);
}
Monitor.Exit (locker);
return aread;
}
示例10: SetHeadersAsync
internal WebAsyncResult SetHeadersAsync (bool setInternalLength, AsyncCallback callback, object state)
{
if (headersSent)
return null;
string method = request.Method;
bool no_writestream = (method == "GET" || method == "CONNECT" || method == "HEAD" ||
method == "TRACE");
bool webdav = (method == "PROPFIND" || method == "PROPPATCH" || method == "MKCOL" ||
method == "COPY" || method == "MOVE" || method == "LOCK" ||
method == "UNLOCK");
if (setInternalLength && !no_writestream && writeBuffer != null)
request.InternalContentLength = writeBuffer.Length;
if (sendChunked || request.ContentLength > -1 || no_writestream || webdav) {
headersSent = true;
headers = request.GetRequestHeaders ();
var result = new WebAsyncResult (callback, state);
result.InnerAsyncResult = cnc.BeginWrite (request, headers, 0, headers.Length, new AsyncCallback (SetHeadersCB), result);
if (result.InnerAsyncResult != null)
return result;
}
return null;
}
示例11: WriteRequest
internal void WriteRequest ()
{
if (requestWritten)
return;
requestWritten = true;
if (sendChunked)
return;
if (!allowBuffering || writeBuffer == null)
return;
byte [] bytes = writeBuffer.GetBuffer ();
int length = (int) writeBuffer.Length;
if (request.ContentLength != -1 && request.ContentLength < length) {
nextReadCalled = true;
cnc.Close (true);
throw new WebException ("Specified Content-Length is less than the number of bytes to write", null,
WebExceptionStatus.ServerProtocolViolation, null);
}
if (!headersSent) {
string method = request.Method;
bool no_writestream = (method == "GET" || method == "CONNECT" || method == "HEAD" ||
method == "TRACE");
if (!no_writestream)
request.InternalContentLength = length;
byte[] requestHeaders = request.GetRequestHeaders ();
WebAsyncResult ar = new WebAsyncResult (null, null);
SetHeadersAsync (requestHeaders, ar);
ar.AsyncWaitHandle.WaitOne ();
if (ar.Exception != null)
throw ar.Exception;
}
if (cnc.Data.StatusCode != 0 && cnc.Data.StatusCode != 100)
return;
IAsyncResult result = null;
if (length > 0)
result = cnc.BeginWrite (request, bytes, 0, length, null, null);
if (!initRead) {
initRead = true;
WebConnection.InitRead (cnc);
}
if (length > 0)
complete_request_written = cnc.EndWrite (request, result);
else
complete_request_written = true;
}
示例12: SetHeadersAsync
internal void SetHeadersAsync (byte[] buffer, WebAsyncResult result)
{
if (headersSent)
return;
headers = buffer;
long cl = request.ContentLength;
string method = request.Method;
bool no_writestream = (method == "GET" || method == "CONNECT" || method == "HEAD" ||
method == "TRACE");
bool webdav = (method == "PROPFIND" || method == "PROPPATCH" || method == "MKCOL" ||
method == "COPY" || method == "MOVE" || method == "LOCK" ||
method == "UNLOCK");
if (sendChunked || cl > -1 || no_writestream || webdav) {
headersSent = true;
try {
result.InnerAsyncResult = cnc.BeginWrite (request, headers, 0, headers.Length, new AsyncCallback(SetHeadersCB), result);
if (result.InnerAsyncResult == null) {
// when does BeginWrite return null? Is the case when the request is aborted?
if (!result.IsCompleted)
result.SetCompleted (true, 0);
result.DoCallback ();
}
} catch (Exception exc) {
result.SetCompleted (true, exc);
result.DoCallback ();
}
} else {
result.SetCompleted (true, 0);
result.DoCallback ();
}
}
示例13: BeginGetResponse
public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
{
if (Aborted)
throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
if (method == null)
throw new ProtocolViolationException ("Method is null.");
string transferEncoding = TransferEncoding;
if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
throw new ProtocolViolationException ("SendChunked should be true.");
Monitor.Enter (locker);
getResponseCalled = true;
if (asyncRead != null && !haveResponse) {
Monitor.Exit (locker);
throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
"method while a previous call is still in progress.");
}
asyncRead = new WebAsyncResult (this, callback, state);
WebAsyncResult aread = asyncRead;
initialMethod = method;
aread.InnerAsyncResult = CheckIfForceWrite (GetResponseAsyncCB, aread);
if (aread.InnerAsyncResult == null)
GetResponseAsyncCB2 (aread);
else
Monitor.Exit (locker);
return aread;
}
示例14: CheckFinalStatus
// Returns true if redirected
bool CheckFinalStatus (WebAsyncResult result)
{
if (result.GotException) {
bodyBuffer = null;
throw result.Exception;
}
Exception throwMe = result.Exception;
HttpWebResponse resp = result.Response;
WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
HttpStatusCode code = 0;
if (throwMe == null && webResponse != null) {
code = webResponse.StatusCode;
if ((!auth_state.IsCompleted && code == HttpStatusCode.Unauthorized && credentials != null) ||
(ProxyQuery && !proxy_auth_state.IsCompleted && code == HttpStatusCode.ProxyAuthenticationRequired)) {
if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
// Keep the written body, so it can be rewritten in the retry
if (MethodWithBuffer) {
if (AllowWriteStreamBuffering) {
if (writeStream.WriteBufferLength > 0) {
bodyBuffer = writeStream.WriteBuffer;
bodyBufferLength = writeStream.WriteBufferLength;
}
return true;
}
//
// Buffering is not allowed but we have alternative way to get same content (we
// need to resent it due to NTLM Authentication).
//
if (ResendContentFactory != null) {
using (var ms = new MemoryStream ()) {
ResendContentFactory (ms);
bodyBuffer = ms.ToArray ();
bodyBufferLength = bodyBuffer.Length;
}
return true;
}
} else if (method != "PUT" && method != "POST") {
bodyBuffer = null;
return true;
}
if (!ThrowOnError)
return false;
writeStream.InternalClose ();
writeStream = null;
webResponse.Close ();
webResponse = null;
bodyBuffer = null;
throw new WebException ("This request requires buffering " +
"of data for authentication or " +
"redirection to be sucessful.");
}
}
bodyBuffer = null;
if ((int) code >= 400) {
string err = String.Format ("The remote server returned an error: ({0}) {1}.",
(int) code, webResponse.StatusDescription);
throwMe = new WebException (err, null, protoError, webResponse);
webResponse.ReadAll ();
} else if ((int) code == 304 && allowAutoRedirect) {
string err = String.Format ("The remote server returned an error: ({0}) {1}.",
(int) code, webResponse.StatusDescription);
throwMe = new WebException (err, null, protoError, webResponse);
} else if ((int) code >= 300 && allowAutoRedirect && redirects >= maxAutoRedirect) {
throwMe = new WebException ("Max. redirections exceeded.", null,
protoError, webResponse);
webResponse.ReadAll ();
}
}
bodyBuffer = null;
if (throwMe == null) {
bool b = false;
int c = (int) code;
if (allowAutoRedirect && c >= 300) {
b = Redirect (result, code, webResponse);
if (InternalAllowBuffering && writeStream.WriteBufferLength > 0) {
bodyBuffer = writeStream.WriteBuffer;
bodyBufferLength = writeStream.WriteBufferLength;
}
if (b && !unsafe_auth_blah) {
auth_state.Reset ();
proxy_auth_state.Reset ();
}
}
if (resp != null && c >= 300 && c != 304)
resp.ReadAll ();
return b;
}
//.........这里部分代码省略.........
示例15: GetResponseAsyncCB2
void GetResponseAsyncCB2 (WebAsyncResult aread)
{
if (haveResponse) {
Exception saved = saved_exc;
if (webResponse != null) {
Monitor.Exit (locker);
if (saved == null) {
aread.SetCompleted (true, webResponse);
} else {
aread.SetCompleted (true, saved);
}
aread.DoCallback ();
return;
} else if (saved != null) {
Monitor.Exit (locker);
aread.SetCompleted (true, saved);
aread.DoCallback ();
return;
}
}
if (!requestSent) {
requestSent = true;
redirects = 0;
servicePoint = GetServicePoint ();
abortHandler = servicePoint.SendRequest (this, connectionGroup);
}
Monitor.Exit (locker);
}