-6

我必须在 c# 中创建几个执行图形遍历函数的任务,现在我想做的是有两个独立的线程,它们将不同的源作为该遍历函数的参数并在任务本身中启动。我有一个使用任务的想法,因为我希望 4 个任务以并行方式工作,但让它们使用两个执行相同功能的线程?那可能吗?

所以我想要的是,task1包含thread1thread2& task2包含thread3thread4&task3包含thread5thread6

所有这些线程都执行相同的功能。是否可以实施?还有其他方法吗?

4

1 回答 1

0
  1. 声明一个可用于将参数传递给线程的类:
class ThreadParamsClass
{
    internal int int1, int2;

    internal ThreadParamsClass(int int1, int int2)
    {
        this.int1 = int1;
        this.int2 = int2;
    }
}
  1. 创建该类的多个实例并启动线程,将参数对象传递给线程:
ThreadParamsClass[] ThreadParams = new ThreadParamsClass[6];
ThreadParams[0] = new ThreadParamsClass(1, 2);
ThreadParams[1] = new ThreadParamsClass(3, 4);
ThreadParams[2] = new ThreadParamsClass(5, 6);
ThreadParams[3] = new ThreadParamsClass(7, 8);
ThreadParams[4] = new ThreadParamsClass(9, 10);
ThreadParams[5] = new ThreadParamsClass(11, 12);
for (int i = 0; i < 6; i++)
{
    Thread Thread1 = new Thread(new ParameterizedThreadStart(Function1));
    Thread1.Start(ThreadParams[i]);
}

void Function1(object Params)
{
    ThreadParamsClass ThreadParams = (ThreadParamsClass)Params;
    int result = ThreadParams.int1 + ThreadParams.int2;
}
于 2013-03-27T14:00:45.647 回答