How to use ThreadPool in C #?

When I run this code, nothing is displayed on the console, but when I debug it, it outputs the output. Please explain why this is happening. How can I get information when Thread completes a task?

public class TestClass
{
    static void Main()
    {
        ThreadPool.SetMaxThreads(5, 5);
        for (int x = 0; x < 10; x++)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(printnum), x);
        }

        Console.ReadKey();
    }

    public static void printnum(object n)
    {
        Console.WriteLine("Call " + n);
        for (int i = 0; i < 10; i++) { Console.WriteLine(i); }
    }
}
+4
source share
3 answers

From the documentation for Console.ReadKey():

The ReadKey method waits, that is, blocks the thread issuing the ReadKey until a key or function key is pressed.

What he actually does is get a lock on Console.InternalSyncObject, which prevents further operations on the console.

The method Console.ReadLine()does not block the thread in this way. You can use it instead.

, .NET 4.5?

+4

. , Console.ReadLine. - , Console.ReadKey. . Microsoft ThreadPool.

    static void Main(string[] args)
    {
        const int count = 10;
        var waitHandles = new ManualResetEvent[count];

        ThreadPool.SetMaxThreads(5, 5);
        for (int x = 0; x < count; x++)
        {
            var handle = new ManualResetEvent(false);
            waitHandles[x] = handle;
            var worker = new MyWorker(handle, x);
            ThreadPool.QueueUserWorkItem(new WaitCallback(MyWorker.printnum), worker);
        }

        WaitHandle.WaitAll(waitHandles);

        Console.WriteLine("Press any key to finish");
        Console.ReadKey();
    }

    class MyWorker
    {
        readonly ManualResetEvent handle;
        readonly int number;

        public MyWorker(ManualResetEvent handle, int number)
        {
            this.handle = handle;
            this.number = number;
        }

        public static void printnum(object obj)
        {
            var worker = (MyWorker)obj;
            Console.WriteLine("Call " + worker.number);
            for (int i = 0; i < 10; i++) { Console.WriteLine(i); }

            // we are done
            worker.handle.Set();
        }
    }

, WaitHandles. , true, . , true.

+1

Console.ReadKey(); Thread.Sleep(9000);, , .

-1

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


All Articles