您的位置:首页 > 其它

在指定的CEF线程上执行任务

2016-02-16 13:05 549 查看
CEF有几种线程,比如TID_UI、比如TID_RENDER,每种都有特定的含义,具体类别定义在cef_types.h中,摘录如下:

[code]typedef enum {
// BROWSER PROCESS THREADS -- Only available in the browser process.

  ///
  // The main thread in the browser. This will be the same as the main
  // application thread if CefInitialize() is called with a
  // CefSettings.multi_threaded_message_loop value of false.
  ///
  TID_UI,

  ///
  // Used to interact with the database.
  ///
  TID_DB,

  ///
  // Used to interact with the file system.
  ///
  TID_FILE,

  ///
  // Used for file system operations that block user interactions.
  // Responsiveness of this thread affects users.
  ///
  TID_FILE_USER_BLOCKING,

  ///
  // Used to launch and terminate browser processes.
  ///
  TID_PROCESS_LAUNCHER,

  ///
  // Used to handle slow HTTP cache operations.
  ///
  TID_CACHE,

  ///
  // Used to process IPC and network messages.
  ///
  TID_IO,

// RENDER PROCESS THREADS -- Only available in the render process.

  ///
  // The main thread in the renderer. Used for all WebKit and V8 interaction.
  ///
  TID_RENDERER,
} cef_thread_id_t;


关于这些线程的说明,看上面代码里的注释,另外亦可以参开这里:https://bitbucket.org/chromiumembedded/cef/wiki/GeneralUsage#markdown-header-threads

我们要想在某个线程上执行任务,比如你在Browser进程里想弹出个窗口,就要在TID_UI线程上来执行你的代码。类似这种任务,可以通过CefTask来完成。很简单,cef_task.h里有CefTask接口的声明,我们继承它,然后再使用CefPostTask即可。

代码类似下面:

[code]#include "include/cef_task.h"

void doSomethingOnUIThread()
{
    MessageBox(...);
}

class SomeTask : public CefTask
{
    IMPLEMENT_REFCOUNTING(SomeTask);
public:
    void Execute()
    {
        doSomethingOnUIThread();
    }
};

void doSomething()
{
    if (CefCurrentlyOn(TID_UI))
    {
        doSomethingOnUIThread();
    }
    else
    {
        CefRefPtr<SomeTask> t = new SomeTask;
        CefPostTask(TID_UI, t);
    }
}


如果你不想自己写一个类实现CefTask接口,CEF还有一些辅助手段来帮到你。先看下面的代码片段:

[code]if (!CefCurrentlyOn(TID_UI)) 
{
    // Execute on the UI thread.
    CefPostTask(TID_UI,
        base::Bind(&ClientHandler::CloseAllBrowsers, this, force_close));
    return;
}


这是CefSimple里的,它使用了base::Bind来生成一个Functor,用法类似STL的bind,包含”include/base/cef_bind.h”头文件即可。

就这样吧。

其他参考文章详见我的专栏:【CEF与PPAPI开发】。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: