Oxygine  1
2g game engine
AsyncTask.h
1 #pragma once
2 #include "oxygine-include.h"
3 #include "core/ThreadDispatcher.h"
4 #include "EventDispatcher.h"
5 #include "Event.h"
6 #include "core/oxygine.h"
7 #ifdef ERROR
8 #undef ERROR
9 #endif
10 
11 namespace oxygine
12 {
13  DECLARE_SMART(AsyncTask, spAsyncTask);
14 
15  class AsyncTaskEvent: public Event
16  {
17  public:
18  AsyncTaskEvent(eventType type, AsyncTask* t) : Event(type), task(t) {}
19  AsyncTask* task;
20  };
21 
22 
23  class AsyncTask: public EventDispatcher
24  {
25  public:
26  enum
27  {
28  ERROR = sysEventID('A', 'T', 'E'),
29  PROGRESS = sysEventID('A', 'T', 'P'),
30  COMPLETE = Event::COMPLETE,
31  };
32 
33  enum status
34  {
35  status_not_started,
36  status_inprogress,
37  status_completed,
38  status_failed
39  };
40 
41 
42  AsyncTask();
43  ~AsyncTask();
44 
45  status getStatus() const { return _status; }
46  void setStatus(status s) { _status = s; }
47  void run();
48 
49  protected:
50  void onError();
51  void onComplete();
52 
53  status _status;
54 
55  friend class AsyncTaskManager;
56 
57  bool _mainThreadSync;
58 
59  virtual bool _prerun() { return true; }
60  virtual void _run() = 0;
61  virtual void _onError() {}
62  virtual void _onComplete() {}
63  virtual void _onFinal(bool error) {}
64  virtual void _finalize(bool error) {}
65  virtual void _dispatchComplete();
66  virtual std::string _getRunInfo() const { return ""; }
67 
68 
69  template <class F>
70  void sync(const F& f, bool addref = true)
71  {
72  if (_mainThreadSync)
73  {
74  if (addref)
75  {
76  addRef();
77  if (!core::isMainThread())
78  sleep(10);
79 
80 
81  core::getMainThreadDispatcher().postCallback([ = ]()
82  {
83  f();
84  releaseRef();
85  });
86  }
87  else
88  {
89  core::getMainThreadDispatcher().postCallback(f);
90  }
91 
92  return;
93  }
94  f();
95  }
96 
97  void _complete();
98  void _error();
99 
100  private:
101  };
102 }
Definition: Event.h:10
void sleep(timeMS)
–oxgl-end–!
Definition: Actor.h:14
Definition: AsyncTask.h:15
Definition: EventDispatcher.h:27
Definition: AsyncTask.h:23