0

在这里,我试图通过读取每个属性 id 的 xml 文档来生成动态线程,但是我面临一个问题,即如何将参数传递给动态线程,对于特定属性的哪些相关元素,有没有办法发送参数?请指教

在下面的线程中,我正在调用一个 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)

这就是我向你们询问传递参数的任何解决方案的原因,注意这里我的线程方法是通过动态方式设计的,请问有什么建议吗?

4

2 回答 2

0

您已经很好地传递了参数。我不确定我是否理解你的问题,但是

我必须传递哪个特定属性 id 的元素的参数我该怎么做?

听起来您所需要的只是if statement您的foreach. 您已经在循环并创建线程/传递参数。您只是在问如何确保每个项目都有一个特定的属性 id?如果是这样 - 就让它

foreach (XElement host in xDoc.Descendants("Host"))
{
    var hostID = (int) host.Attribute("id");
    // Check ID here
    if(hostID != ID_I_WANT) 
        continue;
    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());
}
于 2012-06-11T07:38:30.127 回答
0

您是否能够使用 TPL 而不是启动自己的线程?

如果是这样,您可以这样做:

xDoc.Descendants("Host").AsParallel().ForAll(host =>
{
    DoWork(new FileInfo
    {
        HostId = (int)xe.Attribute("id"),
        Extension = (string)xe.Element("Extension"),
        FolderPath = (string)xe.Element("FolderPath"),
    });
});

还是我错过了这个问题的重点?

于 2012-06-11T07:51:58.117 回答