Threaded simultaneous jobs
There is an array of strings myDownloadList containing 100 string URIs. I want to start 5 jobs on a thread that will call the next URI from myDownloadList (like the stack) and do something with it (load it) until there is no URI left on the stack (myDownloadList).
What would be the best practice for this?
+2
source to share
2 answers
Use ThreadPool and just customize all your requests. ThreadPool will automatically assign them accordingly.
This will get easier with .NET 4 using the parallel task library. Setting up each request as a Task is very efficient and easy.
+6
source to share
Make sure every thread blocks myDownloadList when accessing it. You can use recursion to get the last one, then when the list is 0 it can just stop the function.
See example below.
public static List<string> MyList { get; set; }
public static object LockObject { get; set; }
static void Main(string[] args)
{
Console.Clear();
Program.LockObject = new object();
// Create the list
Program.MyList = new List<string>();
// Add 100 items to it
for (int i = 0; i < 100; i++)
{
Program.MyList.Add(string.Format("Item Number = {0}", i));
}
// Start Threads
for (int i = 0; i < 5; i++)
{
Thread thread = new Thread(new ThreadStart(Program.PopItemFromStackAndPrint));
thread.Name = string.Format("Thread # {0}", i);
thread.Start();
}
}
public static void PopItemFromStackAndPrint()
{
if (Program.MyList.Count == 0)
{
return;
}
string item = string.Empty;
lock (Program.LockObject)
{
// Get first Item
item = Program.MyList[0];
Program.MyList.RemoveAt(0);
}
Console.WriteLine("{0}:{1}", System.Threading.Thread.CurrentThread.Name, item);
// Sleep to show other processing for examples only
System.Threading.Thread.Sleep(10);
Program.PopItemFromStackAndPrint();
}
+1
source to share