Shuji Shuji - 6 months ago 130
SQL Question

C# / Oracle SQL - using BackgroundWorker to connect with database

I have another trobule with my database connection. I'm using Oracle's ManagedDataAccess Client (from NuGet). I created some form with label and progress bar to just show that program is connecting with DB. It just contains 2 elements from designer, so I won't focus on that. I don't care about the effects, as well.

I want to connect with Oracle DB in background, while that progress bar is moving.

public ConnectionState Connect(string connectionString = defaultConnectionString)
{
//form that contains progress bar with Marquee style
ConnectingProgressBar pb = new ConnectingProgressBar();
pb.Show();
//background worker - to connect with DB
BackgroundWorker bwConn = new BackgroundWorker();
ManualResetEvent doneEvent = new ManualResetEvent(false);
bwConn.DoWork += (sender, e) =>
{
db = new OracleConnection(defaultConnectionString);
db.Open();
//while (db.State == ConnectionState.Connecting) Thread.Yield();
};
bwConn.RunWorkerCompleted += (sender, e) =>
{
doneEvent.Set();
};
bwConn.RunWorkerAsync();
doneEvent.WaitOne();
pb.Close();
pb.Dispose();
return db.State;
}


My code doesn't allow me to get effect like that. It got stuck during the initialize form - I had no response from the form, and database won't connect, after all. I also tried OracleConnection's OpenAsync() method, but it has no difference.

Will WaitOne() method work like it should there?

Also, how should I do my 'Connecting' problem? I used to do it like this, just to wait until Connecting phase is finished, but it won't be any good when I use multithreading, will it?

Oh, also tried to make threads by myself, with the very same effect. Tried to pass WaitHandles as well, but it was no good.

Thanks for help!

Answer

You can use your BackgroundWorker if you make a few minor changes, like closing your Form in the RunWorkerCompleted event. And you can get rid of the ManualResetEvent.

ConnectingProgressBar pb = new ConnectingProgressBar();

BackgroundWorker bwConn = new BackgroundWorker();
bwConn.DoWork += (sender, e) =>
{
    db = new OracleConnection(defaultConnectionString);
    db.Open();
};
bwConn.RunWorkerCompleted += (sender, e) =>
{
    if (e.Error != null)
    {
        // An exception was thrown, handle accordingly
    }

    pb.Close();
    pb.Dispose();
};
bwConn.RunWorkerAsync();

pb.ShowDialog();

return db.State;
Comments