How to upload a file using WebClient in C # with running event handlers and supporting the timeout property?

I am developing a C # project to download files from the Internet.

I will show how they progress at boot time. And I have to maintain the timeout property.

I tried using the WebClient class. There are functions DownloadFile () and DownloadFileAsync ().

  • When I use the DownloadFile () function, I can set the Timeout property by overriding the GetWebRequest () function. However, I cannot run event handlers, so I cannot show progress.
  • When I use the DownloadFileAsync () function, I can run event handlers so that I can show the progress. But in this case, I can not set Timeout.

From the Internet, I can find several articles on how to manually set a timeout using streams.

However, I believe that they are all wrong. They set a timeout during the entire boot process. But the download will be short or long depending on the file size.

How can I solve this problem?

+4
source share
2 answers

In the MSDN documentation for HttpWebRequest, you need to implement this yourself using threading.

In the case of asynchronous requests, the client application is responsible for implementing its timeout mechanism. The following code example shows how to do this.

The link above provides a complete example of how to do this using the thread pool and ManualResetEvent (an example is about 50-100 lines of code).

Here is the gist of the above solution with the code given in the MSDN example.

  • Use asynchronous BeginGetResponse.

    Result IAsyncResult = (IAsyncResult) myHttpWebRequest.BeginGetResponse (new AsyncCallback (RespCallback), myRequestState);

  • Use ThreadPool.RegisterWaitForSingleObject to implement a timeout.

    ThreadPool.RegisterWaitForSingleObject (result.AsyncWaitHandle, new WaitOrTimerCallback (TimeoutCallback), myHttpWebRequest, DefaultTimeout, true);

  • Use ManualResetEvent to hold the main thread until the request is complete or completed.

    public static ManualResetEvent allDone = new ManualResetEvent (false); allDone.WaitOne ();

+1
source

All Articles