如何在C#中的后台线程上进行异步数据库调用

时间:2015-01-29 18:17:44

标签: c# mysql multithreading asynchronous

我正在做一些数据库代码。在某些时候,我确实需要将这些调用从UI线程移到后台线程上。我已经在下面发布了我的代码,但我很好奇这样做的一些例子,或者如果有人可以展示如何做到这一点。我已经完成了Java中的异步调用,试图用Visual Studio 2013来完成这个C#。我们将不胜感激。

数据库代码:

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

调用数据库代码:

savedProj = ProjectDbInteraction.QueryProject(currentProjDb);

1 个答案:

答案 0 :(得分:3)

你应该对BackgroundWorker https://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker%28v=vs.110%29.aspx和一般的C#进行一些研究。

我会尝试使用看起来像这样的后台工作者:

//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;
}