summaryrefslogtreecommitdiffstats
path: root/extensions/browser/api/async_api_function.h
blob: f10950684a8b82eb0e9bbda280b3415672b1d1ef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef EXTENSIONS_BROWSER_API_ASYNC_API_FUCTION_H_
#define EXTENSIONS_BROWSER_API_ASYNC_API_FUCTION_H_

#include "content/public/browser/browser_thread.h"
#include "extensions/browser/extension_function.h"

namespace extensions {

// AsyncApiFunction provides convenient thread management for APIs that need to
// do essentially all their work on a thread other than the UI thread.
class AsyncApiFunction : public AsyncExtensionFunction {
 protected:
  AsyncApiFunction();
  ~AsyncApiFunction() override;

  // Like Prepare(). A useful place to put common work in an ApiFunction
  // superclass that multiple API functions want to share.
  virtual bool PrePrepare();

  // Set up for work (e.g., validate arguments). Guaranteed to happen on UI
  // thread.
  virtual bool Prepare() = 0;

  // Do actual work. Guaranteed to happen on the thread specified in
  // work_thread_id_.
  virtual void Work();

  // Start the asynchronous work. Guraranteed to happen on requested thread.
  virtual void AsyncWorkStart();

  // Notify AsyncIOApiFunction that the work is completed
  void AsyncWorkCompleted();

  // Respond. Guaranteed to happen on UI thread.
  virtual bool Respond() = 0;

  // ExtensionFunction::RunAsync()
  bool RunAsync() override;

 protected:
  content::BrowserThread::ID work_thread_id() const { return work_thread_id_; }
  void set_work_thread_id(content::BrowserThread::ID work_thread_id) {
    work_thread_id_ = work_thread_id;
  }

 private:
  void WorkOnWorkThread();
  void RespondOnUIThread();

  // If you don't want your Work() method to happen on the IO thread, then set
  // this to the thread that you do want, preferably in Prepare().
  content::BrowserThread::ID work_thread_id_;
};

}  // namespace extensions

#endif  // EXTENSIONS_BROWSER_API_ASYNC_API_FUCTION_H_