我不得不承認,這個問題還不是特別清楚。但是如果你正在爲每個主機創建一個新的線程,那麼這個怎麼樣?這是使用.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; }
}
這對我來說仍然是the best guide to 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
}
只是生成線程列表或數組,並添加新的線程。 –