2017-02-09 104 views
1

我需要测试客户端服务器应用程序。我有服务器运行在某个端口上,需要创建大约2000个连接服务器的客户端。对于这个我尝试使用下面的代码创建线程时系统内存不足

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); 
     } 
    } 
} 

这里例外发生在System.OutOfmemoryfor loop of Main method
但是我已经检查应用程序消耗时此异常只筹集到110 MB内存中创建在C#应用程序2000多个线程?

为什么c#不让我在数字中创建线程..? 我也试过Thread Pool但不能正常工作...

+0

我可以使用'ThreadPool' –

回答

1

有多少线程可以创建。你可以检查this answer,虽然旧,但仍然给你一瞥。

我也读过C# 5.0 in a Nutshell,每个线程大概需要1MB,这就是为什么在大多数情况下任务比线程更好的解决方案。这也是为什么有一个线程池;因为准备和创建大量线程需要一些时间。

其次,阻塞不会产生零成本。这是因为每个 线程只要占用大约1MB的内存,并且会导致CLR和 操作系统的持续管理开销。由于这个原因,在需要数百或数千并发操作的大量I/O限制程序的情况下,阻塞可能是麻烦的。相反,这样的程序需要在等待时完全使用基于回调的方法,rescind- 。这是(部分)我们稍后将讨论的异步模式的姿态。