0

请帮助我,因为我在网上找不到任何解决方案,我试图做一些 THREAD 函数来从一毫秒访问数据库(.mdb)中选择查询。另一个词..针对相同的 ms 访问数据库 (.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
                }
            }
4

1 回答 1

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

于 2013-03-25T15:15:14.563 回答