c# – Multithreaded iteration of an array


Hello. There is the following code that loads a file with words into an array, let's say the contents of the file are:

Привет Пока Магазин Телефон Монитор .... // и т.д. Очень много слов

You need to make threads for this code. I haven't figured out how yet.

class Test

    static string Text;
    static string[] ReadFile;
    static int Threads;

    static void Main()

        Console.Write("Введите слово которое необходимо проверить: ");
        Text = Console.ReadLine();

        Console.Write("Введите количество потоков: ");
        Threads = Convert.ToInt32(Console.ReadLine());

        ReadFile = System.IO.File.ReadAllLines("slova.txt");

        for (int i = 0; i < Threads; i++) // ну типо потоки запускаем
            (new Thread(new ThreadStart(Slova))).Start();

    static void Slova()

       for (int i = 0; i < ReadFile.Length; i++)
            if (ReadFile[i] == Text)
              Console.Write("Слово " + Text + " успешно найдено в файле " + ReadFile);

The fact is that this code finds a line in the file and checks it against the Text variable as many times as there are threads, that is, if there are 50 threads, then it will take the first line from the file and check it 50 times, then the second, and so on, and the message about finding the string is also 50 times.

Can be done in place for

foreach (string textline in ReadFile) { .. } // тоже самое будет

How to fix it? To make the threads work well. I'm not very familiar with C#. Help me please.


You start a new thread for each iteration of the loop. So it turns out 50 threads. Use a ready-made multi-threaded loop.

    Parallel.For(0, length, i =>
       // Тело цикла.

learn more about Parallel.For

Or divide the loop into N parts by length and create a thread in each part. Get an N-thread loop.

Scroll to Top