TaskMng.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using System.Collections.Concurrent;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading;
  5. using App.Robot.Station.Logical.Model;
  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, Task> tasks = new ConcurrentDictionary<int, Task>();
  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. var task = new Task(config);
  39. task.id = key;
  40. return tasks.TryAdd(key, task);
  41. }
  42. public bool Start(int id)
  43. {
  44. if (tasks.TryGetValue(id, out var task))
  45. {
  46. task.Start();
  47. return true;
  48. }
  49. return false;
  50. }
  51. public bool Stop(int id)
  52. {
  53. if (tasks.TryGetValue(id, out var task))
  54. {
  55. task.Stop();
  56. return true;
  57. }
  58. return false;
  59. }
  60. public bool Remove(int id)
  61. {
  62. if (tasks.TryGetValue(id, out var task))
  63. {
  64. task.Stop();
  65. tasks.TryRemove(id, out _);
  66. return true;
  67. }
  68. return false;
  69. }
  70. public List<Task> GetAll()
  71. {
  72. return tasks.Values.ToList();
  73. }
  74. }
  75. }