2015-06-27 107 views
1

工作的一個.NET控制檯應用程序,其處理用戶請求,並且每一個處理的請求的結果被髮送回用戶(使用TCP套接字)用於測試目的我已經建立我應該使用線程池或任務並行庫

少數線程在多線程上完成這項工作,但轉向生產,我需要能夠儘可能多地處理併發請求。

我很困惑使用ThreadPool或TPL。 (每個請求的平均處理時間是3秒)有什麼建議?

這裏是我當前的代碼:

public void Start() 
    { 
     started = true; 
     Thread looper = new Thread(new ThreadStart(BufferRunner)); 
     looper.Start(); 
     Thread looper2 = new Thread(new ThreadStart(BufferRunner)); 
     looper2.Start(); 
     Thread looper3 = new Thread(new ThreadStart(BufferRunner)); 
     looper3.Start(); 
     Thread looper4 = new Thread(new ThreadStart(BufferRunner)); 
     looper4.Start(); 
    } 

    private void BufferRunner() 
    { 
     while (started) 
     { 
      BufferedCommand command = null; 
      lock (buffer) 
      { 
       if (buffer.Count > 0) 
        command = buffer.Dequeue();//buffer.Enqueue happens when user request is received 
      } 
      if (command != null) 
       ExecuteCommand(command); 
     } 
    } 

回答

3

總是傾向於TPL高於ThreadThreadPool。很難找到使用舊API的原因。 Task提供了可組合性,更好的錯誤處理和await

每個請求的平均處理時間爲3秒

聽起來像LongRunning選項可以是合適的。調查一下。

+0

我實現了一個帶有任務的版本,並將運行一些測試。但是,我仍然不確定是否應該使用'LongRunning'選項,但仍然瞭解任務。謝謝! – Salem

0

您應該使用TPL,因爲它會提供一個更高層次的抽象ThreadPool更好。