TaskMng.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. using System.Collections.Concurrent;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading;
  5. using App.Robot.Station.Logical.Worker;
  6. using Newtonsoft.Json;
  7. using Vit.Core.Util.ConfigurationManager;
  8. namespace App.Robot.Station.Logical
  9. {
  10. public class TaskMng
  11. {
  12. static TaskMng LoadTaskMng()
  13. {
  14. var taskMng = JsonFile.GetFromFile<TaskMng>(new[] { "Data", "App.Robot.json" }) ;
  15. if (null == taskMng)
  16. {
  17. taskMng= new TaskMng();
  18. }
  19. taskMng.tasks.Values.Where(m => m.config.autoStart).ToList().ForEach(task => task.Start());
  20. return taskMng;
  21. }
  22. public static readonly TaskMng Instance = LoadTaskMng();
  23. public void TaskMngSaveToCache()
  24. {
  25. JsonFile.SetToFile(this, new[] { "Data", "App.Robot.json" });
  26. }
  27. [JsonProperty]
  28. ConcurrentDictionary<int, IWorker> tasks = new ConcurrentDictionary<int, IWorker>();
  29. [JsonProperty]
  30. int curKeyIndex = 0;
  31. public TaskMng()
  32. {
  33. }
  34. private int GetNewKey() => Interlocked.Increment(ref curKeyIndex);
  35. public bool Add(TaskConfig config)
  36. {
  37. var key = GetNewKey();
  38. IWorker task;
  39. switch (config.type)
  40. {
  41. case "ApiClientAsync": task = new Worker_ApiClientAsync(config); break;
  42. case "HttpClient": task = new Worker_HttpClient(config); break;
  43. case "HttpUtil": task = new Worker_HttpUtil(config); break;
  44. default: config.type = "ApiClient"; task = new Worker_ApiClient(config); break;
  45. }
  46. task.id = key;
  47. return tasks.TryAdd(key, task);
  48. }
  49. public bool Start(int id)
  50. {
  51. if (tasks.TryGetValue(id, out var task))
  52. {
  53. task.Start();
  54. return true;
  55. }
  56. return false;
  57. }
  58. public bool Stop(int id)
  59. {
  60. if (tasks.TryGetValue(id, out var task))
  61. {
  62. task.Stop();
  63. return true;
  64. }
  65. return false;
  66. }
  67. public bool Remove(int id)
  68. {
  69. if (tasks.TryGetValue(id, out var task))
  70. {
  71. task.Stop();
  72. tasks.TryRemove(id, out _);
  73. return true;
  74. }
  75. return false;
  76. }
  77. public List<IWorker> GetAll()
  78. {
  79. return tasks.Values.ToList();
  80. }
  81. }
  82. }