问题描述
由于无法在线找到任何解决方案,请帮助我,我已尝试执行一些THREAD函数以从一个ms访问数据库(.mdb)中选择查询.另一个针对同一ms ms的线程函数访问数据库(.mdb)...总是失败.这是代码:
Please help me since I couldn't find any solution online, i have tried to do some THREAD function to select query from one ms access database (.mdb).Another word..the thread function targeting to the same ms access db (.mdb) ...and it's always fail. Here is the code :
private void Form1_Load(object sender, EventArgs e)
{
Thread th1 = new Thread(new ThreadStart(method1));
Thread th2 = new Thread(new ThreadStart(method2));
th1.Start();
th2.start();
}
private void method1()
{
using (OleDbConnection odbConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dbfileName + ";Mode=Read"))
{
//db manipulation1
}
}
private void method2()
{
using (OleDbConnection odbConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dbfileName + ";Mode=Read"))
{
//db manipulation2
}
}
推荐答案
您可能想使用 BackgroundWorker 而不是Thread
.此类旨在在后台线程中执行工作.如果要在工作完成后更新UI,可以订阅RunWorkerCompleted事件.此事件的处理程序将在UI线程上运行,您可以在其中安全地更新UI元素.
You might want to use BackgroundWorker instead of Thread
. This class is design to perform work in a background thread. If you want to update the UI after the work is finished, you can subscribe to the RunWorkerCompleted event. Your handler for this event will run on the UI thread where you can safely update UI elements.
private void Form1_Load(object sender, EventArgs e)
{
BackgroundWorker bg1 = new BackgroundWorker();
bg1.DoWork += new DoWorkEventHandler(method1);
bg1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(method1_Completed);
bg1.RunWorkerAsync();
BackgroundWorker bg2 = new BackgroundWorker();
bg2.DoWork += new DoWorkEventHandler(method2);
bg2.RunWorkerCompleted += new RunWorkerCompletedEventHandler(method2_Completed);
bg2.RunWorkerAsync();
}
public void method1(object Sender, DoWorkEventArgs e)
{
using (OleDbConnection odbConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dbfileName + ";Mode=Read"))
{
//db manipulation1
}
}
void method1_Completed(object sender, RunWorkerCompletedEventArgs e)
{
// Update UI.
}
public void method2(object Sender, DoWorkEventArgs e)
{
using (OleDbConnection odbConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dbfileName + ";Mode=Read"))
{
//db manipulation1
}
}
void method2_Completed(object sender, RunWorkerCompletedEventArgs e)
{
// Update UI.
}
请注意,您可以使用DoWorkEventArgs Results属性将对象从DoWork处理程序传递到RunWorkerCompleted处理程序.
Note that you can use the DoWorkEventArgs Results property to pass an object from the DoWork handler to the RunWorkerCompleted handler.
这篇关于具有线程的多个MS ACCESS连接(oledb)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!