/// <summary> /// 下载失败 /// </summary> void OnFailed(emErrorCode code) { lock (lock_obj_) { if (content_ != null) { content_.State = DownloadContent.emState.Failed; content_.Close(); content_ = null; } if (http_request_ != null) { http_request_.Abort(); http_request_ = null; } IsDone = true; ErrorCode = code; if (error_callback_ != null) { error_callback_(this); } } }
/// <summary> /// /// </summary> void _OnReadCallback(IAsyncResult ar) { try { lock (lock_obj_) { DownloadContent rs = ar.AsyncState as DownloadContent; if (rs.ResponseStream == null) { return; } int read = rs.ResponseStream.EndRead(ar); if (read > 0) { rs.FS.Write(rs.Buffer, 0, read); rs.FS.Flush(); CompletedLength += read; if (notify_callback_ != null) { notify_callback_(this, (long)read); } } else { OnFinish(); if (notify_callback_ != null) { notify_callback_(this, (long)read); } return; } _BeginRead(new AsyncCallback(_OnReadCallback)); } } catch (WebException e) { Debug.LogWarning("HttpAsyDownload - \"" + LocalName + "\" download failed!" + "\nMessage:" + e.Message); OnFailed(emErrorCode.DownloadError); } catch (System.Exception e) { Debug.LogWarning("HttpAsyDownload - \"" + LocalName + "\" download failed!" + "\nMessage:" + e.Message); OnFailed(emErrorCode.DownloadError); } }
/// <summary> /// 下载完成 /// </summary> void OnFinish() { lock (lock_obj_) { if (content_ != null) { content_.State = DownloadContent.emState.Completed; content_.Close(); content_ = null; } if (http_request_ != null) { http_request_.Abort(); http_request_ = null; } IsDone = true; } }
/// <summary> /// 开始下载 /// </summary> public void Start(string root, string local_file_name , Action <HttpAsyDownload, long> notify = null , Action <HttpAsyDownload> error_cb = null) { lock (lock_obj_) { Abort(); Root = root; LocalName = local_file_name; IsDone = false; ErrorCode = emErrorCode.None; notify_callback_ = notify; error_callback_ = error_cb; content_ = new DownloadContent(FullName, false); CompletedLength = 0; Length = 0; _Download(); } }