2012-01-24 24 views
5

我有一个统计在某个文件夹中文件的方法:C#:方法名预计

private void countfiles(string path) 
    { 
     if (path != "") 
     { 
      DirectoryInfo dir = new DirectoryInfo(path); 

      foreach (FileInfo filesindires in dir.GetFiles()) 
      { 
       if (filesindires.FullName != Application.ExecutablePath) 
       { 
        num_files++; 
        Thread.Sleep(1); 
       } 
      } 

      foreach (DirectoryInfo dirsinfolder in dir.GetDirectories()) 
      { 
       countfiles(dirsinfolder.FullName); 
      } 
     }   
    } 

并且当计数按钮,用户点击我想作一个线程,所以程序不挂。

Thread count = new Thread(new ThreadStart(countfiles(@"E:/test"))); 

但我甚至调试之前得到这个错误:

Method Name Expected 

我不明白;那个错误需要我什么?

终于非常感谢您的帮助提前。

回答

10

这是

Thread count = new Thread(new ParameterizedThreadStart(countfiles));  
count.Start(@"E:/test"); 

您不必传递的参数,只是方法名。

您还需要将参数的类型更改为object而不是string。另外,如果你想保持string参数,你可以使用:

Thread count = new Thread(
    o => 
    { 
     countFiles((string)o);  
    }); 
count.Start(@"E:/test"); 
+0

谢谢你的工作:) –

3

看一看的ParameterizedThreadStart委托。这会为你传递价值。

Thread count = new Thread(countfiles); 
count.Start(@"E:/test"); 
+1

丹尼尔打败了我。 – Almo

1

的构造函数的ThreadStart预计你的代码看起来像:

Thread count = new Thread(new ThreadStart(countfiles)); 
count.Start(); 

它需要知道要执行哪个方法,而不是结果。但是,因为你有一个参数,你需要做的是这样的:

Thread count = new Thread(new ParameterizedThreadStart(countFiles)); 
count.Start(@"E:/test"); 
6

的问题是在这里:

new ThreadStart(countfiles(@"E:/test")) 

的参数是一个方法调用试图伪装成方法-group。编译器可以将兼容的方法组,lambda表达式或匿名方法转换为委托类型而不是方法调用。

尝试其中之一:

// Lambda 
var thread = new Thread(() => countfiles(@"E:/test")); 

// Anonymous method 
var thread = new Thread(delegate() { countfiles(@"E:/test"); }); 

如果你想使用的方法组,你需要一个单独的方法:

private void CountTestFiles() 
{ 
    countFiles(@"E:/test"); 
} 

,然后你可以这样做:

// Method-group 
var thread = new Thread(CountTestFiles) 

您也可以使用ParameterizedThreadStart委托类型和的相关重载构造函数,但由于参数是object,所以处理起来有些尴尬,所以在某个地方或另一个地方施放将是不可避免的。