创建多个线程的源代码出错

时间:2016-07-08 06:41:59

标签: c# multithreading

我在C#中编写了以下代码来创建多个线程(这里为ex 10)

ThreadStart MainThread = new ThreadStart(CallThread);
for (int i = 1; i <= 10; i++)
{
    Thread ChildThread + Convert.ToString(i) = new Thread(MainThread);    
    ChildThread + Convert.ToString(i).Start();
}

它在第4行提供错误cannot resolve symble ChildThread,在第5行提供Cannot resolve symbol Start

有人可以帮我解决这个问题吗?

4 个答案:

答案 0 :(得分:1)

您无法连接数据以在c#中生成变量名。

您可以使用词典模拟相同的行为:

Dictionary<String, Thread> _threads = new Dictionary<String, Thread>(10);
for (int i = 1; i <= 10; i++)
{   
    _threads.Add("ChildThread" + Convert.ToString(i),new Thread(MainThread) )
    _threads["ChildThread" + Convert.ToString(i)].Start();
}

修改

根据您的第二个要求,您可以将状态传递给您的线程,该状态可以是文件列表:

List<FileInfo> listOfFiles = //some way to get your files
for (int i = 1; i <= 10; i++)
{   
    _threads.Add("ChildThread" + Convert.ToString(i),new Thread(MainThread) )
    _threads["ChildThread" + Convert.ToString(i)].Start( _listOfFiles.Skip(i*5).Take(5).ToList());
}

在你的CallThread函数中:

private void CallThread(Object state) {
    List<FileInfo> filesToProcess = state as List<FileInfo>;
    if(filesToProcess == null) return;
    foreach(FileInfo f in filesToProcess) {
        //do something
    }
}

答案 1 :(得分:0)

如果您需要引用子线程,可以将它们保存在列表变量中:

ThreadStart MainThread = new ThreadStart(CallThread);
List<Thread> threads = new List<Thread>();
        for (int i = 1; i <= 10; i++)
        {
            Thread childThread = new Thread(MainThread);    
            threads.Add(childThread)
            childThread.Start();
        }

答案 2 :(得分:0)

您无法为变量创建动态名称。对于C#来说,你接近的方式是完全错误的。它虽然可以用于脚本语言(即javascript)。这是一个如何创建它们的小例子。

ThreadStart MainThread = new ThreadStart(CallThread);
List<Thread> thList = new List<Thread>(); // It will contain all the threads. If you don't need buffering threads, don't use it.
for (int i = 1; i <= 10; i++)
{
    Thread th = new Thread(MainThread);
    thList.Add(th);
    th.Start();
}

答案 3 :(得分:0)

我认为命名线程就是你想要的。

线程可以具有Name属性。示例如下:

var thread = new Thread(() =>
{
    TheMethodYouWantToExecute(passedVariable);
});
thread.Name = "nameThatIsAString";
thread.Start();

代码将使用lambda表达式创建一个线程(不必是),并将启动刚刚创建的线程。

您可以将“主题”变量添加到List<> ThreadList<>个对象(让我们将var wantedThread = threadList.Where(t => t.Name == "nameThatIsAString").Single(); 命名为 threadList “),然后通过以下代码访问它们:

.url()

祝你有愉快的一天!如果事情不清楚,我会尝试更好地解释它。