Alen Alen - 6 months ago 60
C# Question

How to run database functions in the background?

I am working on C# windows forms and have come across this problem

I have two forms and in first form user enters username and press button. Button calls a function that saves username in database.

private void btn_Click(object sender, EventArgs e)
{
Database db = new Database();
db.SaveUsername(txtUsername.Text);
new Form2().Show();
}


and this
SaveUsername()
function is in separate class

class Database
{
public void SaveUsername(string username)
{
Connect(); //Connection to database
//Some lines to save username in database
}
}


My problem is when user hits enter it takes a bit time to open
Form2
so I want that new form should come up and
SaveUsername()
function runs in background without having user to wait for it to complete. How is it done?

Answer Source

change your method signature and use Async method like :

private async Task  btn_Click(object sender, EventArgs e)
{
    Database db = new Database();
    await db.SaveUsernameAsync(txtUsername.Text);
    new Form2().Show();
}


class Database
{
    public async Task  SaveUsername(string username)
    {
        Connect(); //Connection to database
        //Some lines to save username in database
        ....
        await db.SaveAsync();
    }
}

OR save User in a new thread:

private async Task btn_Click(object sender, EventArgs e)
{
    Database db = new Database();
    await Task.Run(() => SaveUsername(txtUsername.Text));    
    new Form2().Show();
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download