I wrote a method that downloads some files, and now I'm trying to load it up to 5 files in parallel, and the rest is until the previous ones end. For this, I use ManualResetEvent, but when I turn on the syncronisation part, it doesnβt download anything else (it works without it).
Here is the code for the methods:
static readonly int maxFiles = 5;
static int files = 0;
static object filesLocker = new object();
static System.Threading.ManualResetEvent sync = new System.Threading.ManualResetEvent(true);
public void DoanloadFileAsync(string filename)
{
...
System.Threading.ThreadPool.QueueUserWorkItem(
(o) =>
{
bool loop = true;
while (loop)
if (sync.WaitOne())
lock (filesLocker)
{
if (files < maxFiles)
{
++files;
if (files == maxFiles)
sync.Reset();
loop = false;
}
}
try
{
WebClient downloadClient = new WebClient();
downloadClient.OpenReadCompleted += new OpenReadCompletedEventHandler(downloadClient_OpenReadCompleted);
downloadClient.OpenReadAsync(new Uri(url, UriKind.Absolute));
}
catch
{
lock (filesLocker)
{
--files;
sync.Set();
}
throw;
}
});
}
void downloadClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
try
{
...Download logic...
}
finally
{
lock (filesLocker)
{
--files;
sync.Set();
}
}
}
Am I doing something wrong?
This is written using Silverlight 4 for Windows Phone 7.
Edit: In Silverlight 4 there is no semaphore or semaphore Slim.
source
share