yams
yams

Reputation: 952

How to do Asyncronous Database calls on a background thread in C#

I'm doing work on some database code. At some point I do need to move these calls off of the UI thread and on to a Background thread. I've got my code posted below but I'm curious as to some examples for doing this or if someone could show how to do this. I've done Async Calls in Java just trying to wrap my head around doing this C# with Visual Studio 2013. Any help would be appreciated.

Database Code :

    static public Project.Project QueryProject(string projDatabaseName)
    {
        Project.Project proj = new Project.Project();
        string connStr = "server=localhost;database=" + projDatabaseName + ";user=******;port=3306;password=*****;";
        string queryStr = "SELECT * FROM " + projDatabaseName + ".project";
        MySqlConnection myConnection = new MySqlConnection(connStr);
        MySqlCommand myCommand = new MySqlCommand(queryStr, myConnection);
        myConnection.Open();

        try
        {
            MySqlDataReader myReader = myCommand.ExecuteReader();
            while (myReader.Read())
            {
                proj.ProjectID = int.Parse(myReader["ProjectID"].ToString());
                proj.ProjectName = myReader["ProjectName"].ToString();
                proj.ProjectStartDate = Convert.ToDateTime(myReader["ProjectStartDate"]);
                proj.ProjectEndDate = Convert.ToDateTime(myReader["ProjectEndDate"]);
                proj.ProjectNotes = myReader["ProjectNotes"].ToString();
            }
            myReader.Close();

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
            return null;
        }
        finally
        {
            myConnection.Close();
        }
        return proj;
    }

Call to database code:

savedProj = ProjectDbInteraction.QueryProject(currentProjDb);

Upvotes: 0

Views: 980

Answers (1)

Joe Brunscheon
Joe Brunscheon

Reputation: 1989

You should do some research into BackgroundWorker https://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker%28v=vs.110%29.aspx and Threading in general with C#.

I would try using a background worker that would look something like this:

//setting up your background worker.
var worker = new BackgroundWorker();
worker.DoWork += bgw_DoWork;
worker.RunWorkerCompleted += bgw_WorkCompleted;
worker.ProgressChanged += bgw_ProgressChanged;

private void bgw_DoWork(object sender, DoWorkEventArgs e)
{   
    e.Result = ProjectDbInteraction.QueryProject(currentProjDb);
}

private void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    //Here you can inspect the worker and update UI if needed.
}

private void bgw_WorkCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    //check for errors, and other unexpected results first...
    //assuming that savedProj is some private member variable of your class, 
    //just assign the variable to the Result here.
    savedProj = (Project.Project)e.Result;
}

Upvotes: 3

Related Questions