首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >电子:在另一个线程中执行sqlite (更好的sqlite) db操作。

电子:在另一个线程中执行sqlite (更好的sqlite) db操作。
EN

Stack Overflow用户
提问于 2018-01-31 08:01:04
回答 1查看 1.7K关注 0票数 0

我正在开发一个使用电子框架的桌面应用程序,我必须使用sqlite数据库来处理应用程序数据。我决定使用better-sqlite3是因为:

  1. 自定义SQL函数支持(对我来说非常重要)
  2. 在大多数情况下,它比node-sqlite3快得多
  3. 使用起来很简单。
  4. 它是同步API (在大多数情况下,我需要将数据序列化)

但是在某些情况下,当我执行一个需要一段时间来响应的查询时,应用程序UI在查询结束之前不会响应用户。

如何在另一个线程中运行一些db查询?或者运行它们异步化(如node-sqlite3)?

抱歉英语不太好

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-02-01 08:28:28

节点允许您使用单独的进程。(线程是另一回事,唉,没有WebWorkers :(尽管您可以在库中找到一个线程附加项)。

编辑:自从我最初发布这个答案以来,Node就添加了worker_threads。还没有试过/不知道它们是否与更好的sqlite一起工作.结束编辑

我遇到了与您相同的问题--需要同步代码才能运行而不阻塞主线程,并且我使用了一个子进程。它是为了更好

问题是,如何处理io流和sigints等控件并不明显,取决于您是在windows上运行还是在posix上运行。

我使用分叉子进程并将静默选项设置为true来执行同步db工作。

如果需要控制该进程或进度更新报告,则在同步操作期间返回到gui的主进程;我在子进程代码的各个点使用fileSystem writeFileSync / readFileSync对子进程stdin/out进行读写,从而控制/与子进程通信(在同步操作期间不能使用正常的进程间通信api,因为这是事件驱动的,在同步代码运行时不能操作。虽然你可以混合和匹配这两种类型的io)

分叉式儿童加工的实例;

代码语言:javascript
复制
//parent.js and child.js in same folder

//parent.js
process.on('exit', (code) => {
  console.log(`Parent to exit with code: ${code}`);
});

const readLine = require("readline") ;
const cp = require('child_process');

var forkOptions = {
    //execArgv:['--inspect-brk'], // uncomment if debugging the child process
    silent:true // child gets own std pipes (important) whch are piped to parent
};
var childOptions = [] ;
const child = cp.fork(`./child.js`,childOptions,forkOptions);


//for messages sent from child via writeSync
const childChannel = readLine.createInterface({
    input: child.stdout
}).on("line",function(input){
    console.log("writeSync message received from child: " + input) ;
});

//for messages sent from child via process.send
child.on('message', (m) => { 
    console.log("process.send message received from child: " + m) ;
});


// Child.js
process.on('exit', (code) => {
  console.log(`Child to exit with code: ${code}`);
});

const fs = require('fs');

function doSyncStuff(){    
    for(let i = 0 ; i < 20 ; i++){
        //eg. sync db calls happening here
        process.send(`Hello via process.send from child. i = ${i} \n`); // async commms . picked up by parent's "child.on" event
        fs.writeFileSync(process.stdout.fd,`Hello via writeFileSync from child. i = ${i} \n`) ; // sync comms. picked up by parent's readLine listener ("process" here is the child )           
    }
}

doSyncStuff();
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48537273

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档