Bear in mind that more threads doesn’t mean you’ll download the 100 files
faster. There will be an optimal number which you’ll need to test to find
out what that is. When I did something like this a few years ago something
in the order of 10 threads at a time produced the fastest result. That was
on a pc though.
This is how I'd do it. I've used a similar technique before in a console
app. Haven’t got my Mac close at hand so I haven’t compiled it in MT. Should
compile OK through.
You need to run the this on a backgroud thread so not to lock up the UI.
ThreadPool.QueueUserWorkItem(StartDownload);
private void StartDownload(object state)
{
Queue<string> urls = new Queue<string>();
for (int i = 1; i <= 100; i++)
{
urls.Enqueue("www.google.com");
}
Downloader downloader = new Downloader();
downloader.Start(urls, () => EndDownload());
}
private void EndDownload()
{
// Invoke alert message on main thread.
//InvokeOnMainThread()
}
public class Downloader
{
public void Start(Queue<string> urls, Action callback)
{
// Max threads at one time.
// Experiment with this number to find optimal number.
int threadCount = 10;
List<Thread> threads = new List<Thread>();
for (int i = 1; i <= threadCount; i++)
{
// Use Thread objects so that we are not limited by
ThreadPool.
Thread thread = new Thread(new
ParameterizedThreadStart(DoWork));
thread.Start(urls);
threads.Add(thread);
}
// Wait for all to complete before returning.
foreach (Thread thread in threads)
{
thread.Join();
}
callback.Invoke();
}
private void DoWork(object arg)
{
Queue<string> urls = (Queue<string>)arg;
string url;
while (GetNextUrl(urls, out url))
{
try
{
// Download code goes here...
}
catch (WebException)
{
// Make sure you handle download errors.
// Put back in queue to try again.
// You may need some max tries logic to prevent failures
from having this go forever.
lock (urls)
{
urls.Enqueue(url);
}
}
}
}
private bool GetNextUrl(Queue<string> urls, out string url)
{
url = null;
lock (urls)
{
if (urls.Count == 0)
{
return false;
}
url = urls.Dequeue();
return true;
}
}
}
--
View this message in context:
http://monotouch.2284126.n4.nabble.com/Threading-best-practice-tp4411605p4412653.html
Sent from the MonoTouch mailing list archive at Nabble.com.
_______________________________________________
MonoTouch mailing list
[email protected]
http://lists.ximian.com/mailman/listinfo/monotouch