TheadPoolEx.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. namespace SuperSocket.Common
  7. {
  8. /// <summary>
  9. /// Thread pool extension class
  10. /// </summary>
  11. public static class TheadPoolEx
  12. {
  13. /// <summary>
  14. /// Resets the thread pool.
  15. /// </summary>
  16. /// <param name="maxWorkingThreads">The max working threads.</param>
  17. /// <param name="maxCompletionPortThreads">The max completion port threads.</param>
  18. /// <param name="minWorkingThreads">The min working threads.</param>
  19. /// <param name="minCompletionPortThreads">The min completion port threads.</param>
  20. /// <returns></returns>
  21. public static bool ResetThreadPool(int? maxWorkingThreads, int? maxCompletionPortThreads, int? minWorkingThreads, int? minCompletionPortThreads)
  22. {
  23. if (maxWorkingThreads.HasValue || maxCompletionPortThreads.HasValue)
  24. {
  25. int oldMaxWorkingThreads, oldMaxCompletionPortThreads;
  26. ThreadPool.GetMaxThreads(out oldMaxWorkingThreads, out oldMaxCompletionPortThreads);
  27. if (!maxWorkingThreads.HasValue)
  28. maxWorkingThreads = oldMaxWorkingThreads;
  29. if (!maxCompletionPortThreads.HasValue)
  30. maxCompletionPortThreads = oldMaxCompletionPortThreads;
  31. if (maxWorkingThreads.Value != oldMaxWorkingThreads
  32. || maxCompletionPortThreads.Value != oldMaxCompletionPortThreads)
  33. {
  34. if (!ThreadPool.SetMaxThreads(maxWorkingThreads.Value, maxCompletionPortThreads.Value))
  35. return false;
  36. }
  37. }
  38. if (minWorkingThreads.HasValue || minCompletionPortThreads.HasValue)
  39. {
  40. int oldMinWorkingThreads, oldMinCompletionPortThreads;
  41. ThreadPool.GetMinThreads(out oldMinWorkingThreads, out oldMinCompletionPortThreads);
  42. if (!minWorkingThreads.HasValue)
  43. minWorkingThreads = oldMinWorkingThreads;
  44. if (!minCompletionPortThreads.HasValue)
  45. minCompletionPortThreads = oldMinCompletionPortThreads;
  46. if (minWorkingThreads.Value != oldMinWorkingThreads
  47. || minCompletionPortThreads.Value != oldMinCompletionPortThreads)
  48. {
  49. if (!ThreadPool.SetMinThreads(minWorkingThreads.Value, minCompletionPortThreads.Value))
  50. return false;
  51. }
  52. }
  53. return true;
  54. }
  55. }
  56. }