IPAddressItemHashSet.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System.Threading.Tasks;
  4. namespace FastGithub.DomainResolve
  5. {
  6. /// <summary>
  7. /// IPAddressItem集合
  8. /// </summary>
  9. sealed class IPAddressItemHashSet
  10. {
  11. private readonly object syncRoot = new();
  12. private readonly HashSet<IPAddressItem> hashSet = new();
  13. /// <summary>
  14. /// 获取元素数量
  15. /// </summary>
  16. public int Count => this.hashSet.Count;
  17. /// <summary>
  18. /// 添加元素
  19. /// </summary>
  20. /// <param name="item"></param>
  21. /// <returns></returns>
  22. public bool Add(IPAddressItem item)
  23. {
  24. lock (this.syncRoot)
  25. {
  26. return this.hashSet.Add(item);
  27. }
  28. }
  29. /// <summary>
  30. /// 转换为数组
  31. /// </summary>
  32. /// <returns></returns>
  33. public IPAddressItem[] ToArray()
  34. {
  35. lock (this.syncRoot)
  36. {
  37. return this.hashSet.ToArray();
  38. }
  39. }
  40. /// <summary>
  41. /// Ping所有IP
  42. /// </summary>
  43. /// <returns></returns>
  44. public Task PingAllAsync()
  45. {
  46. var items = this.ToArray();
  47. if (items.Length == 0)
  48. {
  49. return Task.CompletedTask;
  50. }
  51. if (items.Length == 1)
  52. {
  53. return items[0].PingAsync();
  54. }
  55. var tasks = items.Select(item => item.PingAsync());
  56. return Task.WhenAll(tasks);
  57. }
  58. }
  59. }