这里我想通过阅读每个属性id的xml文档生成一个动态线程,但是我面临的一个问题是如何将参数传递给动态线程,特定属性的元素,有没有什么办法可以发送参数?请咨询如何通过使用3.5 c#传递参数到线程.net
在下面的线程我打电话dowork方法,我必须传递其中特定属性id的元素的参数我该怎么做?
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; }
}
如何调用一个线程中需要多个参数的方法。我所说的方法
Send(string arg1, string arg2, string arg3)
,这是我问你们的任何解决方案来传递参数的原因,注意这里我穿线方法是通过动态的方式设计的,任何建议吗?
查看'ParametrizedThreadStart'。 – CodeCaster
@CodeCaster他已经在使用它了,因为'DoWork'需要'object threadState' –
这就引发了这个问题,当然......因为你已经成功地传递了一个参数......真正的问题是什么? –