I'm using ThreadPool to download multiple files from a server. I have a list of files to be downloaded, of which some files are of huge size. I want to download these huge files after downloading other small-sized files. And, I'm using WebClient.DownloadFile()
.
Currently I'm using Thread.Join(time)
to start the threads for huge files to start after some time. But there is no guarantee that the other downloads would have been completed by that time. The value for time
will vary depending on the network speed.
Is there a better solution to handle this? Please help.
Use a ManualResetEvent object and set it inside your process and wait for all reset events. Something like this:
public void DispatchWork(IEnumerable<string> worklist)
{
var resetEvents = new List<ManualResetEvent>();
var batch = 100;
foreach (work in worklist)
{
var resetEvent = new ManualResetEvent(false);
resetEvents.Add(resetEvent);
ThreadPool.QueueUserWorkItem((a) =>
{
try
{
// do work
}
catch (Exception e)
{
// do something
throw;
}
finally
{
if (resetEvent != null) resetEvent.Set();
}
});
}
foreach (var resetEvent in resetEvents)
{
resetEvent.WaitOne();
resetEvent.Dispose(); // todo: use try-finally
}
resetEvents.Clear();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.