0

尝试使用 backgroundworker 从 mdb 读取数据时出现错误

程序“[3768] BackgroundWorkerExample.vshost.exe: Managed”已退出,代码为 0 (0x0)。

没有任何其他信息或异常,我无法抓住它。这是我的代码,没有 BGW 它可以正常工作。我错过了什么吗?

namespace BackgroundWorkerExample
{
public class TestClass
{
    BackgroundWorker _Worker;

    public TestClass()
    {
        InitializeWorker();
    }

    public void InitializeWorker()
    {
        _Worker = new BackgroundWorker();

        _Worker.DoWork += new DoWorkEventHandler(WorkerDoWork);
        _Worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(WorkerRunWorkerCompleted);
    }

    private void WorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        Console.WriteLine("Work completed!");
    }

    private void WorkerDoWork(object sender, DoWorkEventArgs e)
    {
        DataTable data = GetDataTable();
        PrintResults(data);
    }

    public void Run()
    {
        _Worker.RunWorkerAsync();
    }

    public DataTable GetDataTable()
    {
        string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\students.mdb;";

        try
        {
            using (OleDbConnection con = new OleDbConnection(connectionString))
            {
                try
                {
                    con.Open(); // crashes here!

                    DataTable res = new DataTable();

                    string query = "SELECT * FROM students";

                    OleDbDataAdapter adapter = new OleDbDataAdapter(query, con);
                    adapter.Fill(res);

                    return res;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return null;
                }
            }
        }
        catch (Exception e)
        {
            // never reaches this part
            return null;
        }
    }

    public void PrintResults(DataTable data)
    {
        foreach (DataRow row in data.Rows)
        {
            for (int i = 0; i < 5; i++)
            {
                Console.Write(row[i] + "   ");
            }
            Console.WriteLine();
        }
    }
}
}
4

1 回答 1

1

看起来您没有足够的时间来执行BackGroundWorker。快速解决方法是检查 BackGroundWorker 是否忙。如果忙,您可以让您Main thread等待某个时间,以便后台工作人员可以完成其工作。

您看到的消息不是错误,而只是表明线程已关闭(primary and the background worker thread

public void Run()
{
    _Worker.RunWorkerAsync();

     while (_Worker.IsBusy){

        Thread.Sleep(4000);
    }
}
于 2012-11-06T09:40:50.447 回答