我正在从rusqlite
迁移,在那里我使用get_interrupt_handle
立即中止来自另一个线程的查询(当用户更改过滤器参数时).
以下是我当前代码的一个示例.我最多只能在每await
次之前添加一个中断判断,但如果初始查询需要很长时间才能返回第一个结果,那么这并不管用.
struct Query {
title: String,
}
fn start_async(requests: crossbeam::channel::Receiver<Query>) {
thread::spawn(move || {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
runtime.block_on(run_db_thread(requests));
});
}
async fn run_db_thread(requests: crossbeam::channel::Sender<Query>) {
let connection = SqliteConnection::connect("test.sqlite").await?;
loop {
if let Ok(query) = requests.recv() {
do_query(&connection, &query).await?;
}
}
}
async fn do_query(connection: &SqliteConnection, query: &Query) -> Result<(), Box<dyn Error>> {
let mut stream = sqlx::query("SELECT title, authors, series FROM Books where title like ?")
.bind(&format!("%{}%", query.title))
.fetch(&connection);
while let Some(row) = stream.next().await {
let (title, authors, series) = row?;
println!("{} {} {}", title, authors, series);
}
}
当新的Query
到达通道时,有没有办法中断正在运行的SQLX执行?如果需要的话,我很乐意单独发个信号.