C# 线程方法名称预期错误

标签 c# multithreading

我正在尝试创建一个简单的线程过程(假设这是我第一次尝试线程),我想要它做的就是对 string[] 中的每个字符串简单地遍历一个 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
    };
  }

最佳答案

您必须将委托(delegate)传递给线程构造函数。此处最简单的方法是使用 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
    }
}

关于C# 线程方法名称预期错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9910940/

相关文章:

iphone - 为什么对主队列的 dispatch_sync( ) 调用会阻塞主队列?

android - 该应用程序显示即使在后台线程中执行了操作,也在主线程中做了过多的工作

c# - 在 C# 中的循环中使用 ThreadPool

c# - MVC vs ASP.net——证明一个比另一个更容易测试的测试用例

c# - 如何从按下的列表框中获取项目的索引(列表包含与命令绑定(bind)而不是单击的按钮)

c# - 如何在 C# 中使用正则表达式获取某个特定单词之前的数字?

c# - WinCE 6.0,支持GPRS/WiFi

c# - 是否可以检查数据库是否空间不足?

java - Java 中的进程与线程

ios - 超高优先级后台工作或 QUARTZ 精度