protected internal void OnTimeout(object state) { if (!TimeoutEnabled) { return; } if (!_isCompleted && Monitor.TryEnter(Lock)) { if (!_isCompleted) { _isCompleted = true; StopTimer(); try { Request.Abort(); } catch { } } Monitor.Exit(Lock); } }
/// <summary> /// /// </summary> public void Abort() { Aborting = true; Request.Abort(); Thread.Sleep(1); Aborting = false; }
/// <summary> /// 取消 HTTP 请求。 /// </summary> public HttpRequest Canel() { Request.Abort(); State = HttpRequestState.Cancelled; TransferProgressChanged?.Invoke(this, null); return(this); }
// public members public void Abort() { if (Request != null) { Request.Abort(); } }
/// <summary> /// A login threadból (stoplogint=false) hívja Invoke-kal /// </summary> /// <param name="stoplogint"></param> public void ResetAfterLogin(bool stoplogint) { var a = new Action(delegate //2015.04.03. { button1.Enabled = false; Request.Abort(); if (stoplogint) //2014.09.01. { LThread.Abort(); //2014.09.01. } button1.Text = Language.Translate(Language.StringID.Login); button1.Enabled = true; linkLabel1.Enabled = true; textBox1.Enabled = true; //2014.09.01. textBox2.Enabled = true; //2014.09.01. textBox1.ReadOnly = false; //2015.04.08. textBox2.ReadOnly = false; //2015.04.08. }); if (stoplogint) //2015.04.03. { a(); } else { this.Invoke(a); } }
/// <summary> /// 重新构造相同的 HTTP 请求,用于重复当前请求。 /// </summary> public HttpRequest RebuildRequest() { if (State == HttpRequestState.Connecting || State == HttpRequestState.Progressing) { throw new InvalidOperationException("不能对传输中的请求进行修改。"); } var oldRequest = Request; Request = WebRequest.CreateHttp(oldRequest.RequestUri); Request?.Abort(); ResultStream?.Dispose(); Request.Accept = oldRequest.Accept; Request.AllowReadStreamBuffering = oldRequest.AllowReadStreamBuffering; Request.ContentType = oldRequest.ContentType; Request.ContinueTimeout = oldRequest.ContinueTimeout; Request.CookieContainer = oldRequest.CookieContainer; Request.Credentials = oldRequest.Credentials; Request.Headers = oldRequest.Headers; Request.Method = oldRequest.Method; Request.Proxy = oldRequest.Proxy; Request.UseDefaultCredentials = oldRequest.UseDefaultCredentials; State = HttpRequestState.NothingSpecial; return(this); }
private HttpWebResponse GetResponse() { if (Response == null) { HttpWebResponse webResponse = null; try { EnsureParametersSetBeforeCall(); byte[] data = PostData; if (data != null) { Stream requestStream = null; Request.ContentLength = data.Length; try { requestStream = WebClientService.GetRequestStreamWithTimeout(Request, Timeout); } catch (Exception e) { Request.Abort(); throw new WebClientException("Unable to get response from server", e); } try { WebClientService.ExecSyncWithTimeout ( (callback, state) => requestStream.BeginWrite(data, 0, data.Length, callback, state), requestStream.EndWrite, Timeout ); } catch (Exception e) { Request.Abort(); throw new WebClientException("Unable to send data to server", e); } requestStream.Close(); } webResponse = WebClientService.GetResponseWithTimeout(Request, Timeout); } catch (Exception e) { Request.Abort(); throw new WebClientException("Unable to get response from server", e); } if (!IsAcceptedStatusCode(webResponse.StatusCode)) { throw new WebClientException(string.Format("The server did not respond with accepted status code, but with [{0}]", webResponse.StatusCode)); } Response = webResponse; } return(Response); }
/// <summary> /// 释放该次网络请求的资源,在该操作后内部的<see cref="ResultStream" />与<see cref="Response" />不再有效,但不会释放<see cref="SetResultStream" /> /// 所设置的流。 /// </summary> public void Dispose() { Request?.Abort(); Response?.Dispose(); if (_customStream == null) { ((IDisposable)ResultStream)?.Dispose(); } }
public void LateUpdate(float dt) { if (mode == JumpTowardTargetAction.TargetMode.Joint) { float sqrMagnitude = Vector2.SqrMagnitude(caster.Position() - joint.TransformPoint(jtta.offset)); if (sqrMagnitude < Mathf.Pow(0.1f, 2) || IsFinish()) { jumpRequest.Abort(); } } }
private void LoginForm_FormClosing(object sender, FormClosingEventArgs e) { if (LThread != null && LThread.IsAlive) { LThread.Abort(); //2014.03.27. - Na vajon kell-e más Request.Abort(); //2014.03.27. - Kell... Ez } if (CurrentUser.UserID == 0) { Program.Exit(); } }
protected virtual void Dispose(bool disposing) { if (!isDisposed) { if (disposing) { Request.Abort(); Response.Close(); } } isDisposed = true; // 标识此对象已释放 }
public void CancelRequestAttempt() { if (Request != null) { try { Request.Abort(); } // ReSharper disable once EmptyGeneralCatchClause catch { } } }
public void CancelRequestAttempt() { if (Request != null) { try { Request.Abort(); } catch { // ignored } } }
public override bool SetupRequest(CancellationToken cancellationToken) { ServicePointManager.SecurityProtocol = SecurityProtocol; ServicePointManager.ServerCertificateValidationCallback = ServerCertificateValidation; Request = _requestCallback(); Request.ProtocolVersion = ProtocolVersion; Request.UserAgent = $"tModLoader/{ModLoader.versionTag}"; Request.KeepAlive = true; cancellationToken.Register(() => { Request?.Abort(); OnCancel?.Invoke(this); }); return(true); }
public int ResetAfterLogin(bool stoplogint) { button1.Enabled = false; Request.Abort(); if (stoplogint) //2014.09.01. { LThread.Abort(); //2014.09.01. } button1.Text = Language.Translate("login"); button1.Enabled = true; linkLabel1.Enabled = true; textBox1.Enabled = true; //2014.09.01. textBox2.Enabled = true; //2014.09.01. return(0); }
protected void Application_Error() { Exception unhandledException = Server.GetLastError(); HttpException httpException = unhandledException as HttpException; if (httpException == null) { Exception innerException = unhandledException.InnerException; httpException = innerException as HttpException; } // We don't care about operation canceled: http://stackoverflow.com/questions/22157596/asp-net-web-api-operationcanceledexception-when-browser-cancels-the-request var cancelledException = unhandledException as OperationCanceledException; if (cancelledException != null) { var token = cancelledException.CancellationToken; if (token.IsCancellationRequested) { Server.ClearError(); Request.Abort(); return; } } if (httpException != null) { int httpCode = httpException.GetHttpCode(); switch (httpCode) { default: Response.Redirect("~/Home/Error", false); break; } } else { var invalidOperationException = unhandledException as InvalidOperationException; if (invalidOperationException != null) { Server.ClearError(); Request.Abort(); return; } Framework.Logging.LogException(unhandledException); } }
protected virtual void Dispose(bool disposing) { if (disposing) { if (Request != null) { Request.Abort(); } if (Response != null) { Response.Close(); Response.Dispose(); } } }
public void Close() { // parsing done. now free resources asap to avert leaking and memory fragmentation // (this is a known problem w java.net.HttpURLConnection) if (Stream != null) { Stream.Dispose(); Stream = null; } if (Request != null) { Request.Abort(); Request = null; } if (Response != null) { Response.Dispose(); Response = null; } MimeType = null; }
private void LoadData(string key) { if (!NetworkInterface.GetIsNetworkAvailable()) { Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show("Ha habido un error intentando acceder a los nuevos datos o no hay conexiones de red disponibles.\nPor favor asegúrese de contar con acceso de red y vuelva a intentarlo.")); return; } DatosLoaded = false; Canceled = false; if (Request != null) { Request.Abort(); } var client = new HttpClient(); var param = new Dictionary <string, object> { { "id", key } }; Request = client.Get("/api/livetren".ToApiCallUri(param, true)); Request.BeginGetResponse(HTTPWebRequestCallBack, Request); }
public void Close() { try { IsStart = false; if (Response != null) { Response.Close(); } if (Request != null) { Request.Abort(); } if (mThread != null) { mThread.Abort(); } } catch (Exception e) { App.Logger.Error(e.ToString()); } }
/// <summary> /// 根据相传入的数据,得到相应页面数据 /// </summary> /// <param name="item">参数类对象</param> /// <returns>返回HttpResult类型</returns> internal HttpResult GetHtml(HttpItem item) { //返回参数 HttpResult result = new HttpResult { Item = item }; try { //准备参数 SetRequest(item); } catch (Exception ex) { //配置参数时出错 return(new HttpResult() { Cookie = string.Empty, Header = null, Html = ex.Message, StatusDescription = "配置参数时出错:" + ex.Message }); } try { //请求数据 using (Response = (HttpWebResponse)Request.GetResponse()) { GetData(item, ref result); } } catch (WebException ex) { if (ex.Response != null) { using (Response = (HttpWebResponse)ex.Response) { GetData(item, ref result); } } else { result.Html = ex.Message; } } catch (Exception ex) { result.Html = ex.Message; } if (item.IsToLower) { result.Html = result.Html.ToLower(); } //重置request,response为空 if (item.IsReset) { if (Request != null) { Request.Abort(); Request = null; } if (Response != null) { Response.Close(); Response = null; } } return(result); }
private void Update_(float dt) { if (pauseCount > 0) { return; } if (IsFinish()) { return; } elapsed += dt; if (da.ignoreObstacles || da.collision) { dashRequest.Update(dt); Vector3 displacement = ((FixedUpdateDashRequest)dashRequest).Displacement_(movementComponent, dt); if (da.ignoreObstacles) { movementComponent.ForceSetPosition(movementComponent.PositionV3 + displacement); } else { movementComponent.Move(displacement); } } if (da.collision) { Vector2 centerOfHitbox = GetCenterOfHitbox(); Vector2 bridgeHitBoxSize = new Vector2( Mathf.Abs(centerOfHitbox.x - centerOfHitBoxAtPreviousFrame.x), casterBoxCollider.size.y ); Vector2 centerOfBridgeHitBox = (centerOfHitbox + centerOfHitBoxAtPreviousFrame) / 2; /*CubeShape cc = new CubeShape(centerOfBridgeHitBox, bridgeHitBoxSize, new List<SsarTuple<Color, float>>(new []{new SsarTuple<Color, float>(Color.yellow, .1f), })); * GizmosDrawer.Instance.AddRequest(new DrawRequest(cc, .1f));*/ cubeShape.SetPos(centerOfHitbox); cubeShape.size = casterBoxCollider.size; bool collision = false; Transform collidedTransform = null; Collider targetCollider = null; Collider[] c = Physics.OverlapBox(centerOfBridgeHitBox, bridgeHitBoxSize / 2, Quaternion.identity, obstacleMask); foreach (Collider collider in c) { //DLog.Log("Collide with obstacle " + collider.name); if (collider.gameObject == mapGround) { continue; } if (collider.gameObject == mapCeil) { continue; } collision = true; collidedTransform = collider.transform; targetCollider = collider; break; } if (!collision) { c = Physics.OverlapBox(centerOfBridgeHitBox, bridgeHitBoxSize / 2, Quaternion.identity, creatureMask); foreach (Collider collider in c) { //DLog.Log("Collide with creature " + collider.GetComponentInParent<EntityReference>().gameObject.name); EntityReference collidedEntityRef = collider.GetComponentInParent <EntityReference>(); if (collidedEntityRef.transform == casterTransform) { continue; } if (collidedEntityRef.Entity.Group.Equals(casterEntity.Group)) { continue; } collision = true; if (collidedTransform == null) { collidedTransform = collider.transform; targetCollider = collider; } else { float distanceBetweenCasterAndTransform = Vector2.Distance(positionAtPreviousFrame, collider.transform.position); float distanceBetweenCasterAndPreviousTransform = Vector2.Distance(positionAtPreviousFrame, collidedTransform.position); if (distanceBetweenCasterAndTransform < distanceBetweenCasterAndPreviousTransform) { collidedTransform = collider.transform; targetCollider = collider; } } } } if (collision && !dispatched) { Vector2 pos; if (elapsed > dt) //second loop or above //DLog.Log("Second and above loop"); { Vector2 offset = da.offset.FlipFollowDirection(movementComponent.FacingDirection); pos = (Vector2)targetCollider.bounds.center - offset; pos.y = movementComponent.Position.y; float minX = centerOfHitBoxAtPreviousFrame.x - offset.x; float maxX = centerOfHitbox.x - offset.x; if (movementComponent.FacingDirection == Direction.Left) { minX = centerOfHitbox.x - offset.x; maxX = centerOfHitBoxAtPreviousFrame.x - offset.x; } /*if (pos.x < minX || pos.x > maxX) { * DLog.Log("x " + pos.x + " minX " + minX + " maxX " + maxX); * }*/ pos.x = Mathf.Clamp(pos.x, minX, maxX); } else //first loop //DLog.Log("First loop"); { bool alreadyCollided = false; Collider[] collidedCreatures = Physics.OverlapBox(centerOfHitBoxAtPreviousFrame, casterBoxCollider.size / 2, Quaternion.identity, creatureMask); if (collidedCreatures.Contains(targetCollider)) { alreadyCollided = true; } if (alreadyCollided) { pos = positionAtPreviousFrame; } else { Vector2 offset = da.offset.FlipFollowDirection(movementComponent.FacingDirection); pos = (Vector2)targetCollider.bounds.center - offset; if (movementComponent.FacingDirection == Direction.Right) { pos -= new Vector2(targetCollider.bounds.size.x / 2, 0); } else { pos += new Vector2(targetCollider.bounds.size.x / 2, 0); } pos.y = movementComponent.Position.y; } } movementComponent.ForceSetPosition(pos); cubeShape.SetPos(GetCenterOfHitbox()); dispatched = false; skill.TriggerEventWithId(da.eventId); dashRequest.Abort(); } centerOfHitBoxAtPreviousFrame = centerOfHitbox; } positionAtPreviousFrame = movementComponent.Position; if (IsFinish()) { ResetColliderToOriginalValues(); } }
public static void AsyncDownloadFile(object o) { var Param = (ThreadParam)o; HttpWebRequest Request; HttpWebResponse Response; Stream HttpStream; FileStream OutStream; Int32 ReadBytes = 0; Byte[] Buffer = new Byte[1024]; int statictime = System.Environment.TickCount; int CountTime = 0; int CountingBytenum = 0; while (true) { Param.mStartEvent.WaitOne(); if (-1 == Param.mBeginBlock) { Param.mStartEvent.Reset(); Param.mDoneEvent.Set(); continue; } try { Request = WebRequest.Create(Param.url /* + "//" + Param.mFileName*/) as HttpWebRequest; Request.AddRange(Param.mBeginBlock, Param.mEndBlock); Response = Request.GetResponse() as HttpWebResponse; //Response.StatusCode; 这个值为200表示一切OK HttpStream = Response.GetResponseStream(); OutStream = new FileStream(Param.mFileName + Param.mId.ToString(), FileMode.Create); while (true) { ReadBytes = HttpStream.Read(Buffer, 0, Buffer.Length); if (ReadBytes <= 0) { break; } Param.mDownloadSize += ReadBytes; int atime = Environment.TickCount; int deltatime = atime - statictime; CountTime += deltatime; if (CountTime >= 1000) { Param.mSpeed = CountingBytenum; CountTime = 0; CountingBytenum = 0; } else { CountingBytenum += ReadBytes; } statictime = atime; OutStream.Write(Buffer, 0, ReadBytes); } OutStream.Close(); HttpStream.Close(); Response.Close(); Request.Abort(); Param.mStartEvent.Reset(); Param.mDoneEvent.Set(); } catch (WebException e) { } } }
public void Abort() { Request?.Abort(); }
public override void Cancel() { Request.Abort(); }
/// <summary> /// Aborts the request /// </summary> public void Abort() { incapsulatedRequest.Abort(); }
public void Dispose() { Request?.Abort(); }
/// <summary> /// Abort a long running FtpWebRequest /// </summary> public void AbortRequest() { Request.Abort(); }
public override void Cancel() { Logging.tML.Warn($"HttpDownloadRequest [{DisplayText}] was cancelled."); Request?.Abort(); base.Cancel(); }
private void _Download() { try { if (UnCompeleteSize <= 0) { IsCompleted = true; BlockEvents.OnProgress(100, 100); BlockEvents.OnCompleted(); Request.Abort(); return; } Log.Debug(BlockIndex.ToString() + "号文件块开始下载."); Request.Timeout = Timeout.Infinite; Request.Accept = "*/*"; Request.AllowAutoRedirect = true; Request.AddRange(StartPosition + _CompletedPosition); Log.Debug(BlockIndex.ToString() + "号块正在获取网络回应."); var response = (HttpWebResponse)Request.GetResponse(); Log.Debug(BlockIndex.ToString() + "号块正在获取流."); Stream stream = response.GetResponseStream(); if (stream == null) { IsCompleted = true; BlockEvents.OnProgress(100, 100); BlockEvents.OnCompleted(); Request.Abort(); Log.Debug("无法获取到WebRequest请求的相应文件流~"); return; } Log.Debug(BlockIndex.ToString() + "号块正在创建暂存文件."); using (var filestream = new FileStream(FilePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)) { var buffersize = DownloadState.BufferSize; var buffer = new byte[buffersize]; Log.Debug(BlockIndex.ToString() + "号块初始化完毕."); try { while (UnCompeleteSize > 0) { Log.Debug(BlockIndex.ToString() + "号块开始从" + _CompletedPosition.ToString() + "处读取流数据."); int receiveCount = stream.Read(buffer, 0, (int)buffersize); Log.Debug(BlockIndex.ToString() + "号块本次读取流数据长度为" + receiveCount.ToString() + "字节."); if (receiveCount <= 0) { var sb = new StringBuilder(); sb.Append("发生下载阻塞" + "\t"); sb.Append("BlockIndex:" + BlockIndex.ToString() + "\t"); sb.Append("StartPosition:" + (StartPosition + CompletedPosition).ToString() + "\t"); sb.Append("BufferSize:" + BlockSize.ToString() + "\t"); sb.Append("ReceiveCount:" + receiveCount.ToString()); Log.Debug(sb.ToString()); Thread.Sleep(5000); continue; } int availbleReceiveCount = (UnCompeleteSize < receiveCount ? UnCompeleteSize : receiveCount); filestream.Write(buffer, 0, availbleReceiveCount); filestream.Flush(); _CompletedPosition += availbleReceiveCount; Log.Debug(BlockIndex.ToString() + "号块已完成" + _CompletedPosition.ToString() + "/" + this.BlockSize.ToString() + "字节的下载."); BlockEvents.CompletedBytesCount += availbleReceiveCount; if (UnCompeleteSize <= 0 || DownloadState.StopDownload) { break; } } buffer = null; response.Close(); stream.Close(); if (DownloadState.StopDownload) { return; } Log.Debug(BlockIndex.ToString() + "号文件块下载完成."); this.IsCompleted = true; BlockEvents.OnCompleted(); this.Request.Abort(); filestream.Close(); } catch (Exception err) { buffer = null; response.Close(); stream.Close(); filestream.Close(); BlockEvents.OnException(err); this.Request.Abort(); } } } catch (Exception err) { BlockEvents.OnException(err); this.Request.Abort(); } }