void StreamCallback(IAsyncResult result) { FileDownLoad fdl = null; try { fdl = (FileDownLoad)result.AsyncState; Interlocked.Exchange(ref fdl._timecount, 0); int n = fdl._stream.EndRead(result); if (n <= 0) { throw new Exception("HttpWebResponse read exception"); } fdl._file.Write(fdl._buf, 0, n); fdl._file.Flush(); _dsize -= n; //继续读数据 if (_dsize > 0) { OnProgress(fdl); fdl._stream.BeginRead(fdl._buf, 0, _dsize > RecvBuffSize?RecvBuffSize:_dsize, new AsyncCallback(StreamCallback), fdl); } else { OnDownComplete(fdl); } } catch (Exception e) { Log.e(e, Log.Tag.Default, e.StackTrace); OnDownFailed(fdl); } }
static void DownLoadCallBack(EventMgr.EventData eb) { FileDownLoad fdl = eb.data as FileDownLoad; if (null == fdl._onDownload) { return; } fdl._onDownload(fdl); if (fdl.state == State.Doing) { return; } fdl._onDownload = null; }
void OnDownFailed(FileDownLoad fdl) { switch (fdl.action) { case Action.DownFile: fdl._info = _cancel?"下载已暂停":"下载文件失败"; break; case Action.CalcSize: fdl._info = "获取文件大小失败"; break; } fdl._state = State.Failed; fdl.innerStop(); EventMgr.single.PostEvent("DownFileEvent", fdl); }
void ResponseCallback(IAsyncResult result) { FileDownLoad fdl = null; try { fdl = (FileDownLoad)result.AsyncState; Interlocked.Exchange(ref fdl._timecount, 0); fdl._response = fdl._request.EndGetResponse(result) as HttpWebResponse; switch (_action) { case Action.CalcSize: int fsize = File.Exists(_path)?(int)(new FileInfo(_path).Length):0; fdl._size = (int)fdl._response.ContentLength; if (fdl._size <= 0) { throw new Exception("invalid url"); } fdl._dsize = fdl._size - fsize; OnDownComplete(fdl); break; case Action.DownFile: fdl._stream = fdl._response.GetResponseStream(); fdl._size = (int)(_file.Position + fdl._response.ContentLength); fdl._dsize = (int)fdl._response.ContentLength; if (_dsize > 0) { fdl._stream.BeginRead(fdl._buf, 0, _dsize > RecvBuffSize?RecvBuffSize:_dsize, new AsyncCallback(StreamCallback), fdl); } else { OnDownComplete(fdl); } break; } } catch (Exception e) { Log.e(e, Log.Tag.Default, e.StackTrace); OnDownFailed(fdl); } }
void OnDownComplete(FileDownLoad fdl) { fdl._state = State.Completed; fdl.innerStop(); EventMgr.single.PostEvent("DownFileEvent", fdl); }
void OnProgress(FileDownLoad fdl) { EventMgr.single.PostEvent("DownFileEvent", fdl); }