Search code examples
smotask-parallel-library

Executing scripts on databases in the same server concurrently using SMO and Task Parallel Library?


I am trying to concurrently execute update scripts on all Databases in the same Server using SQL Server Management Objects. My current experiment implementation is like this:

var server = new Server(new ServerConnection(new SqlConnection(connString)));
server.ConnectionContext.InfoMessage += new SqlInfoMessageEventHandler(DBOutputReceived);
            
var databases = server.Databases.Cast<Database>().ToList();          
Parallel.ForEach(databases, db => { db.ExecuteNonQuery(script); });
    

I'm not even sure this is possible using SMO, but this is basically what I want to do. I can see that the ConnectionContext.InfoMessage event will likely have issues, but I'm not sure how to resolve. Should I instead create a separate Server instance for each parallel task?


Solution

  • The solution is to have each thread create it's own Server/ServerConnection object, that way there is no shared memory between the threads.