简体   繁体   English

C#中的线程安全数据库访问

[英]Thread safe database access in C#

I have a Winforms application that does some hefty database work. 我有一个Winforms应用程序,它可以完成一些重要的数据库工作。 It does a lot of reading and some inserting of records. 它做了很多阅读和一些记录插入。 The operation can take up to 30 seconds to a minute, depending on the size of the database. 操作最多可能需要30秒到一分钟,具体取决于数据库的大小。 Right now, my program works just fine. 现在,我的程序运行得很好。

My problem is, while my program is doing this, my UI thread is being blocked till the database stuff is done. 我的问题是,当我的程序这样做时,我的UI线程被阻塞,直到数据库的东西完成。 I'd like to put the database functions into a thread, however, according to this MSDN article , ADO.NET is not thread-safe. 我想将数据库函数放入一个线程,但是,根据这篇MSDN文章 ,ADO.NET不是线程安全的。

Is there a way to provide a progress bar on my UI or some way around the "ADO.NET is not thread safe"? 有没有办法在我的UI上提供进度条或某种方式“ADO.NET不是线程安全的”? Maybe to write my own classes that inherit SqlDataReader or SqlConnection to make it thread-safe. 也许编写我自己的继承SqlDataReaderSqlConnection来使其成为线程安全的。 Is this even possible? 这甚至可能吗?

Just use a backgroundworker and make sure each thread (bgw) creates its own Connection object. 只需使用backgroundworker并确保每个线程(bgw)创建自己的Connection对象。

And regarding to the linked article, make sure you have a Concurrency-safe way of generating keys. 关于链接文章,请确保您具有生成密钥的并发安全方法。 Letting the Db generate them is the best option. 让Db生成它们是最好的选择。

Is there a way to provide a progress bar on my UI 有没有办法在我的UI上提供进度条

That's tricky. 这很棘手。 A Bgw can ReportProgress just fine but getting it from a running query is a problem. Bgw可以报告ReportProgress,但是从正在运行的查询中获取它是一个问题。 Even the total nr of rows is usually only known at the end. 甚至总行数nr通常只在最后才知道。
But you can always fake it, the user doesn't mind/know. 但你总是可以假装它,用户不介意/知道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM