1

Let say i have an application that uses a database. And whenever this application starts it backups the database to some location. And this backup process takes too much time.

To make the gui responsive I would use async await. Like this;

public async Task BackupDataBase(){

   using(SqlCommand command = new SqlCommand(@"BACKUP DATABASE [MyDatabase] TO  DISK = 'C:\....\MyDatabase.bak'"), connection)
   {
       await command.ExecuteNonQueryAsync();
   }

}

My question is; Can my application use the same connection to query some other things without any need to lock? Or should i lock the connection while asynchronous method is working?

MOD
  • 1,070
  • 3
  • 19
  • 41
  • 3
    So surely your question is 'is `SqlConnection` thread safe?', not 'are async mathods thread safe?'. Searching will give you lots of results for this. – Charles Mager May 30 '15 at 16:11

1 Answers1

0

Even though you new up a SqlConnection you are effectively requesting a possibly existing instance from a connection pool maintained internally in the SqlConnection class.

Generally speaking it will not be blocking. You can limit the maximum pool size to one, but this would most likely cause most of your app to become very unresponsive and it would be suicide in a web app.

The sql server is generally good at keeping appropriate locks given the nature of your sql statement and my guess is that your code would work.

It is perhaps a little unconventional to make the backup from within your application though, and it would become a mess if your ever scaled the app horizontally to more than one Web server.

So how about a scheduled task on the sql server?

faester
  • 14,886
  • 5
  • 45
  • 56