带线程的多个MS ACCESS连接(oledb)

时间:2013-03-25 14:01:56

标签: c# ms-access

请帮助我,因为我在网上找不到任何解决方案,我试图做一些THREAD函数从一个ms访问数据库(.mdb)中选择查询。 换句话说,线程函数的目标是同一个ms访问db(.mdb)...而且总是失败。这是代码:

            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
                }
            }

1 个答案:

答案 0 :(得分:0)

您可能希望使用BackgroundWorker代替Thread。此类设计用于在后台线程中执行工作。如果要在工作完成后更新UI,可以订阅RunWorkerCompleted事件。此事件的处理程序将在UI线程上运行,您可以在其中安全地更新UI元素。

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处理程序。