我不得不同意这个问题并不是特别清楚。但是,如果您只想为每个主机创建一个新线程,那么这个怎么样?这是使用.NET 4.0 Task Parallel Library。从 .NET 4.0 开始,这是一种利用处理器并发功能的简单方法。
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
}
如果您使用的是 .NET 3.5 或更早版本,那么您可以自己创建线程:
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; }
}
这对我来说仍然是 Threading 的最佳指南。
编辑
所以这是我认为你在评论中得到的基于任务的版本?
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
}