C#threading方法名称预期错误

时间:2012-03-28 15:36:02

标签: c# multithreading

我正在尝试创建一个简单的线程程序(授予这是我第一次尝试线程),我想要它做的就是为字符串[]中的每个字符串简单地通过一个void并执行简单的文件夹爬行。但是,我收到预期的方法名称,我不确定为什么

string[] FileListing = {@"C:\","E:\"};
        foreach (string fl in FileListing)
        {
            ProjectDirectoryProcessing pjp = new ProjectDirectoryProcessing();
            //error here
            Thread oThread = new Thread(new ThreadStart(pjp.ProjectProcessor(fl)));
            oThread.Start();
        }

public class ProjectDirectoryProcessing
{
    public void ProjectProcessor(string rootDirectory)
    {
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
        HashSet<string> DirectoryHolding = new HashSet<string>();
        //do some work
        //foreach loop
    };
  }

4 个答案:

答案 0 :(得分:2)

您必须将委托传递给线程构造函数。这里最简单的方法是使用lambda表达式:

string copy = fl;
Thread oThread = new Thread(() => pjp.ProjectProcessor(copy));

请注意,由于捕获循环变量的方式,您需要复制循环变量。 (有关详细信息,请参阅Eric Lippert's blog post。)

或者,当您在每次迭代时创建一个新的ProjectDirectoryProcessing实例时,您可以将该字符串传递给构造函数

foreach (string fl in FileListing)
{
    // Note change in name to be clearer (IMO)
    ProjectDirectoryProcessor pjp = new ProjectDirectoryProcessor(fl);
    Thread oThread = new Thread(pjp.Execute);
    oThread.Start();
}

...

public class ProjectDirectoryProcessor
{
    private readonly string rootDirectory;

    public ProjectDirectoryProcessor(string rootDirectory)
    {
        this.rootDirectory = rootDirectory;
    }

    public void Execute()
    {
        Stopwatch stopwatch = Stopwatch.StartNew();
        HashSet<string> DirectoryHolding = new HashSet<string>();
        // do some work
        //foreach loop
    }
}

答案 1 :(得分:1)

你需要传递一个委托,你可以用lambda:

来做
 Thread oThread = 
      new Thread( () => pjp.ProjectProcessor(fl));

但是你会捕获一个循环变量,所以把它变成

    foreach (string fl in FileListing)
    {
        string copy = fl;

        ProjectDirectoryProcessing pjp = new ProjectDirectoryProcessing();
        //error here
        Thread oThread = 
          new Thread( () => pjp.ProjectProcessor(copy));
        oThread.Start();
    }

其他

每次制作一个Thread非常昂贵,你最好使用:

    Parallel.ForEach(FileListing, fl => 
      {            
        ProjectDirectoryProcessing pjp = new ProjectDirectoryProcessing();         
        pjp.ProjectProcessor(fl);

      } );
    // when here: all threads are done. 

请注意,现在在线程上创建了pjp

答案 2 :(得分:0)

Thread oThread = new Thread(new ThreadStart(pjp.ProjectProcessor(fl)));

您实际上是将void作为参数传递给ThreadStart构造函数。

答案 3 :(得分:0)

一定是线程吗?任务更适合这一点。换掉:

Thread oThread = new Thread(new ThreadStart(pjp.ProjectProcessor(fl)));
oThread.Start();

使用:

Task.Factory.StartNew(pjp.ProjectProcessor(fl));