My app is using HTMLAgilityPack to parse HTML and System.Data.SqlClient to connect with local database and obtain/insert data.
The thing is that sample of code works without any errors:
Database databaseObject = new Database();
List<Account> accounts = new List<Account>();
...
//Add some data to accounts and databaseObject
...
databaseObject.Open()
foreach (Account account in accounts)
{
accounts.doMagic(this, databaseObject);
}
I did not add databaseObject.Close() to be sure that connection with database exists. Allright, now here is code which not works properly:
Database databaseObject = new Database();
List<Account> accounts = new List<Account>();
...
//Add some data to accounts and databaseObject
...
databaseObject.Open()
foreach (Account account in accounts)
{
Thread thread = new Thread(() => account.doMagic(this, databaseObject ));
thread.Start();
}
this also will not work:
Database databaseObject = new Database();
List<Account> accounts = new List<Account>();
...
//Add some data to accounts and databaseObject
...
databaseObject.Open()
Parallel.ForEach(accounts, account =>
{
account.doMagic(this, databaseObject );
});
It starts to work, but after few seconds I am getting System.InvalidOperationException with information that ExecuteNonQuery requires opened and avaible connection.
What?! Connection should be Opened all the time!
What's more I am getting System.Data.SqlClient.SqlException with info about Timeout Expired
What the hell is going on? I am not closing any connection, so how can it be closed? I can't understand why it is not working properly with implementing a bit multithreading..
locksomewhere