Task.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. //
  2. // Task.cpp
  3. //
  4. // $Id: //poco/1.4/Foundation/src/Task.cpp#1 $
  5. //
  6. // Library: Foundation
  7. // Package: Tasks
  8. // Module: Tasks
  9. //
  10. // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
  11. // and Contributors.
  12. //
  13. // SPDX-License-Identifier: BSL-1.0
  14. //
  15. #include "Poco/Task.h"
  16. #include "Poco/TaskManager.h"
  17. #include "Poco/Exception.h"
  18. namespace Poco {
  19. Task::Task(const std::string& name):
  20. _name(name),
  21. _pOwner(0),
  22. _progress(0),
  23. _state(TASK_IDLE),
  24. _cancelEvent(false)
  25. {
  26. }
  27. Task::~Task()
  28. {
  29. }
  30. void Task::cancel()
  31. {
  32. _state = TASK_CANCELLING;
  33. _cancelEvent.set();
  34. if (_pOwner)
  35. _pOwner->taskCancelled(this);
  36. }
  37. void Task::reset()
  38. {
  39. _progress = 0.0;
  40. _state = TASK_IDLE;
  41. _cancelEvent.reset();
  42. }
  43. void Task::run()
  44. {
  45. TaskManager* pOwner = getOwner();
  46. if (pOwner)
  47. pOwner->taskStarted(this);
  48. try
  49. {
  50. _state = TASK_RUNNING;
  51. runTask();
  52. }
  53. catch (Exception& exc)
  54. {
  55. if (pOwner)
  56. pOwner->taskFailed(this, exc);
  57. }
  58. catch (std::exception& exc)
  59. {
  60. if (pOwner)
  61. pOwner->taskFailed(this, SystemException(exc.what()));
  62. }
  63. catch (...)
  64. {
  65. if (pOwner)
  66. pOwner->taskFailed(this, SystemException("unknown exception"));
  67. }
  68. _state = TASK_FINISHED;
  69. if (pOwner)
  70. pOwner->taskFinished(this);
  71. }
  72. bool Task::sleep(long milliseconds)
  73. {
  74. return _cancelEvent.tryWait(milliseconds);
  75. }
  76. void Task::setProgress(float progress)
  77. {
  78. FastMutex::ScopedLock lock(_mutex);
  79. _progress = progress;
  80. if (_pOwner)
  81. _pOwner->taskProgress(this, _progress);
  82. }
  83. void Task::setOwner(TaskManager* pOwner)
  84. {
  85. FastMutex::ScopedLock lock(_mutex);
  86. _pOwner = pOwner;
  87. }
  88. void Task::setState(TaskState state)
  89. {
  90. _state = state;
  91. }
  92. void Task::postNotification(Notification* pNf)
  93. {
  94. poco_check_ptr (pNf);
  95. FastMutex::ScopedLock lock(_mutex);
  96. if (_pOwner)
  97. {
  98. _pOwner->postNotification(pNf);
  99. }
  100. }
  101. } // namespace Poco