简体   繁体   中英

System out of memory while creating threads

I need to test a client server application. I have server running on some port and need to create around 2000 clients connecting the server. For this i am trying to create 2000 threads in c# application using following code

 class Program
{
    /// <summary>
    /// Sample client code that makes gRPC calls to the server.
    /// </summary>
    public static void Main(string[] args)
    {
        for (int i = 0; i <= 2000; i++)
        {
            CalThread cThread = new CalThread(i);                                          
        } // Exception Raised Here 
    }       
}

 class CalThread
{
    public CalThread(int clientID)
    {            
        Thread thread = new Thread(() => getDataFromServer(clientID));
        thread.Start();
    }
    public void getDataFromServer(int clientID)
    {
        try
        {
            //Channel channel = new Channel("192.168.0.123:50051", ChannelCredentials.Insecure);
            while (true)
            {
               //Some code to connect to server and fetch data
                Thread.Sleep(15000);
            }
        }
        catch (Exception ex)
        {
            Thread.Sleep(15000);
            Console.WriteLine(ex.Message);
        }
    }
}

Here exception occur System.OutOfmemory in for loop of Main method
However i have checked Application consume only 110 MB memory when this exception raised ?

Why c# not let me creating threads in numbers.. ? I have also tried Thread Pool but not working ...

There is a limitation to how many threads you can create. You can check this answer , albeit old, but still gives you a glimpse.

I have also read on C# 5.0 in a Nutshell that it takes about 1MB per a thread, and that is why tasks are better solutions than threads in most cases. That's also why there is a thread pool; because it takes sometime to prepare and create a lot of threads.

Second, blocking does not incur a zero cost. This is because each thread ties up around 1MB of memory for as long as it lives and causes an ongoing administrative overhead for the CLR and operating system. For this reason, blocking can be troublesome in the context of heavily I/O-bound programs that need to han- dle hundreds or thousands of concurrent operations. Instead, such programs need to use a callback-based approach, rescind- ing their thread entirely while waiting. This is (in part) the pur- pose of the asynchronous patterns that we'll discuss later.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM