It seems that SMO was not built in a thread-safe manner. When you call Script() on a Table , it uses some kind of common state from its Server , so you cannot execute it on two tables from the same Server . But you can get around this by creating a new Server object for each Table :
private static TableCollection GetTables() { Server server = new Server(…); Database database = server.Databases[…]; var tables = database.Tables; return tables; } … Parallel.For(0, GetTables().Count, i => { var stringCollection = GetTables()[i].Script(); … });
This will cause your queries to be parallel, but I don’t know if it will do it faster.
EDIT: If you want to create one Server for each thread, you can use Parallel.For() overload, which allows stream-based initialization. Sort of:
Parallel.For(0, GetTables().Count, () => GetTables(), (i, _, tables) => { var stringCollection = tables[i].Script(); … return tables; }, tables => { });
Thus, each thread will have its own Server object, but only one.
svick source share