Make the user choose how many threads he wants?

I am trying to create a C # tool where the user can choose how many threads he wants for the tool to execute at the same time. So, for example, it puts "10" in a threadTextBox, so when he clicks the startButton button, the program will start and perform the desired task on 10 threads at the same time.

Here is the current code that I have for 3 threads, but I don’t know how to get the user to choose how many threads he wants to use.

static void Main(string[] args)
{
    Task task1 = Task.Factory.StartNew(() => doStuff());
    Task task2 = Task.Factory.StartNew(() => doStuff());
    Task task3 = Task.Factory.StartNew(() => doStuff());

    Task.WaitAll(task1, task2, task3);
            Console.WriteLine("Done !");
}

static void doStuff()
{
    // do stuff here
}

Thanks in advance.

+4
source share
3 answers

This seems like the perfect use of arrays:

static void Main(string[] args) {
    var tasks = new Task[n];
    for (int j1 = 0; j1 < n; ++j1)
        tasks[j1] = Task.Factory.StartNew(() => doStuff());

    Task.WaitAll(tasks);
            Console.WriteLine("Done !");
}
+2
source

- .

int numberOfThreads = int.Parse(args[0]);

Enum.Range IEnumerable , LINQ .

static void Main(string[] args)
{
    int numberOfThreads = int.Parse(args[0]);
    Task.WaitAll(
        Enum.Range(0, numberOfThreads)
            .Select(
                Task.Factory.StartNew(() => doStuff())
            )
            .ToArray()
        )
    );
    Console.WriteLine("Done !");
}

Parallel.For, , .

static void Main(string[] args)
{
    int numberOfThreads = int.Parse(args[0]);

    Parallel.For(1, numberOfThreads, (i) => doStuff());
    Console.WriteLine("Done !");
}

, , ParallelOptions. 100 , , .

static void Main(string[] args)
{
    int numberOfThreads = int.Parse(args[0]);

    Parallel.For(
        1, 
        100, 
        new ParallelOptions
        {
            MaxDegreeOfParallelism = numberOfThreads
        },
        (i) => doStuff()
    );
    Console.WriteLine("Done !");
}
0

, , , Task.Factory.StartNew(());? , ^^

-1

Source: https://habr.com/ru/post/1688974/


All Articles