I have an application that has two threads.
The first one (the main thread) that captures the data using socket and update DataTables
The second Inserts the DataTables into the database.
The application works fine but when it closes, the main thread finishes reading the data and call Abort method in the second thread, which may be inserting into database and this leads to inconsistent data.
Currently I am using the following solution to overcome "aborting during insertion"
EDIT: After the powerful answers I changed the code
void MainThread()
{
while(Read())
{
//Read Data through socket
try
{
//Wait on Mutex1
//Update Tables
}
finally
{
//Release Mutex1
}
}
_isrunning = false;
_secondThread.Join();
}
void SecondThread()
{
while(_isrunning)
{
try
{
//Wait on Mutex1
//Insert Tables into Database using transactions
}
finally
{
//Release Mutex1
}
}
}
Assuming "call abort method" means aborting the thread using Thread.Abort. Don't do that.
You are effectively crashing your app. There are plenty cleaner ways of doing this with Monitors.
Nonetheless, you should not be getting inconsistent data in your DB when your app crashes that's why you have DB transactions which have the ACID properties.
VERY IMPORTANT EDIT You said: you do not use transactions for performance reasons, and instead use mutexes. This is WRONG on quite a few levels. Firstly, transactions can make certain operations faster, for example try inserting 10 rows into a table, try it again within a transaction, the transaction version will be faster. Secondly, what happens when/if your app crashes, do you corrupt your DB? What happens when multiple instances of your app are running? Or while you run reports against your DB in query analyzer?