public DownloadState Download(string url, Control ctrl, ProgressDelegate pd) { RequestState myRequestState = new RequestState(); try { // Create a HttpWebrequest object to the desired URL. HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url); // Create an instance of the RequestState and assign the previous myHttpWebRequest // object to its request field. myRequestState.downloadManager = this; myRequestState.request = myHttpWebRequest; myRequestState.ctrl = ctrl; myRequestState.progFormCB = new ProgressFormDelegate(Progress); myRequestState.progCB = new ProgressDelegate( pd ); // Start the asynchronous request. IAsyncResult result = (IAsyncResult)myHttpWebRequest.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState); // this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), myHttpWebRequest, DefaultTimeout, true); // Release the HttpWebResponse resource. //myRequestState.response.Close(); lock (activeDownloads) { activeDownloads.Add(myRequestState); } return (DownloadState)myRequestState; } catch (WebException e) { myRequestState.error = e; myRequestState.progFormCB(myRequestState.progCB, myRequestState); /* Console.WriteLine("\nMain Exception raised!"); Console.WriteLine("\nMessage:{0}", e.Message); Console.WriteLine("\nStatus:{0}", e.Status); Console.WriteLine("Press any key to continue.........."); */ } catch (Exception e) { Console.WriteLine("\nMain Exception raised!"); Console.WriteLine("Source :{0} ", e.Source); Console.WriteLine("Message :{0} ", e.Message); Console.WriteLine("Press any key to continue.........."); //Console.Read(); } return null; }
/// <summary> /// Progress callback, called when we've read another packet of data. /// Used to set info in GUI on % complete & transfer rate. /// </summary> private void Progress(ProgressDelegate pd, RequestState ds) { if (ds.ctrl != null) { if (ds.ctrl.InvokeRequired) { ProgressFormDelegate del = new ProgressFormDelegate(Progress); try { ds.ctrl.Invoke(del, new object[] { pd, ds }); } catch (Exception e) { } } else { pd(ds); } } else { pd(ds); } }