I have to agree that the question is not particularly clear. But if you are looking to just create a new thread for every host, then how about this? This is using the .NET 4.0 Task Parallel Library. From .NET 4.0 onwards this is an easy way to harness the concurrent capabilities of your processor.
static void Main(string[] args)
{
var currentDir = Directory.GetCurrentDirectory();
var xDoc = XDocument.Load(string.Format(Path.Combine(currentDir, "Hosts.xml")));
var taskFactory = new TaskFactory();
foreach (XElement host in xDoc.Descendants("Host"))
{
var hostId = (int) host.Attribute("id");
var extension = (string) host.Element("Extension");
var folderPath = (string) host.Element("FolderPath");
taskFactory.StartNew(() => DoWork(hostId, extension, folderPath));
}
//Carry on with your other work
}
static void DoWork(int hostId, string extension, string folderPath)
{
//Do stuff here
}
If you're using .NET 3.5 or previous, then you can just create the threads yourself:
static void Main(string[] args)
{
var currentDir = Directory.GetCurrentDirectory();
var xDoc = XDocument.Load(string.Format(Path.Combine(currentDir, "Hosts.xml")));
var threads = new List<Thread>();
foreach (XElement host in xDoc.Descendants("Host"))
{
var hostID = (int) host.Attribute("id");
var extension = (string) host.Element("Extension");
var folderPath = (string) host.Element("FolderPath");
var thread = new Thread(DoWork)
{
Name = string.Format("samplethread{0}", hostID)
};
thread.Start(new FileInfo
{
HostId = hostID,
Extension = extension,
FolderPath = folderPath
});
threads.Add(thread);
}
//Carry on with your other work, then wait for worker threads
threads.ForEach(t => t.Join());
}
static void DoWork(object threadState)
{
var fileInfo = threadState as FileInfo;
if (fileInfo != null)
{
//Do stuff here
}
}
class FileInfo
{
public int HostId { get; set; }
public string Extension { get; set; }
public string FolderPath { get; set; }
}
This for me is still the best guide to Threading.
EDIT
So this is the task based version of what I think you're getting at in your comment?
static void Main()
{
var currentDir = Directory.GetCurrentDirectory();
var xDoc = XDocument.Load(string.Format(Path.Combine(currentDir, "Hosts.xml")));
var taskFactory = new TaskFactory();
//I'm assuming this ID would normally be user input, or be passed from some other external source
int hostId = 2;
taskFactory.StartNew(() => DoWork(hostId, xDoc));
//Carry on with your other work
}
static void DoWork(int hostId, XDocument hostDoc)
{
XElement foundHostElement = (from hostElement in hostDoc.Descendants("Host")
where (int)hostElement.Attribute("id") == hostId
select hostElement).First();
var extension = (string)foundHostElement.Element("Extension");
var folderPath = (string)foundHostElement.Element("FolderPath");
//Do stuff here
}