none
一个异步的HTTP下载程序,如何实现在下载期间向主界面报告下载进度? RRS feed

  • 问题

  • 最近用C#编写一个异步的HTTP下载程序,代码大致如下:
    string sResult = "";
    HttpWebRequest request = null;
    try {
    IAsyncResult asyncResult;
    request = (HttpWebRequest)WebRequest.Create(sUrl);
    request.Credentials = CredentialCache.DefaultCredentials;
    request.Method = "GET";
    request.AllowAutoRedirect = false;
    request.KeepAlive = false;
    xstate = new RequestState();
    xstate.FilePath = sLocal;
    xstate.request = request;
    asyncResult = request.BeginGetResponse(new AsyncCallback(ResponseCallback), xstate);
    }
    在回调函数ResponseCallback里面,调用:
    IAsyncResult asynchronousInputRead = responseStream.BeginRead(state.buffer, 0, 4096, new AsyncCallback(ReadCallBack), state); 启动下载数据的异步操作,然后在ReadCallBack里面这样写: RequestState state = (RequestState)asyncResult.AsyncState; try { Stream responseStream = state.dataStream; int read = responseStream.EndRead(asyncResult); if (read > 0) { if (state.fs == null) { state.fs = new FileStream(state.FilePath, FileMode.Create, FileAccess.Write); } state.fs.Write(state.buffer, 0, read); //我希望能够在这个地方向主界面汇报下载的进度。。。。 IAsyncResult asynchronousResult = responseStream.BeginRead(state.buffer, 0, 4096, new AsyncCallback(ReadCallBack), state); return; } else { if (state.fs != null) state.fs.Close(); responseStream.Close(); state.response.Close(); }

    这个程序实际测试能够正确下载文件,但问题没有任何进度报告。。。。我曾经尝试将一个ProgressBar对象传递给ReadCallBack函数,但实际运行的时候会报错说: “线程间操作无效,从不是创建ProgressBar的线程访问。。。。” 现在就不知道应该怎么做了,请专家指点。
    2011年5月24日 15:37

答案

全部回复