Search code examples
c#backgroundworkeroledbconnection

Cannot open OleDbConnection in BackgroundWorker


When trying to read data from mdb using backgroundworker I get an error

The program '[3768] BackgroundWorkerExample.vshost.exe: Managed' has exited with code 0 (0x0).

without any other information or exception and I'm not able to catch it. Here is my code, without BGW it works fine. Do I miss something?

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();
        }
    }
}
}

Solution

  • Looks like you are not giving enough time for the BackGroundWorker to execute.A quick fix would be to check if BackGroundWorker is busy.If it's busy you can make your Main thread to wait for sometime so the background worker can complete its job.

    The message that you are seeing is not an error, but just an indication that the threads have closed down(primary and the background worker thread)

    public void Run()
    {
        _Worker.RunWorkerAsync();
    
         while (_Worker.IsBusy){
    
            Thread.Sleep(4000);
        }
    }