I have Blocking Collection of some lists and I process it in a task - add the data from blocking collection to database. Here is some part of the code:
private static Task _databaseTask;
private static readonly BlockingCollection<List<SomeItem>> DataToBeInsertedToDatabase = new BlockingCollection<List<SomeItem>>();
public static void ProcessInsertsCollection()
{
_databaseTask = Task.Factory.StartNew(() =>
{
foreach (List<SomeItem> data in DataToBeInsertedToDatabase.GetConsumingEnumerable())
{
try
{
DateTime[] dateTimes = data.Select(d => d.ContributionDateTime).ToArray();
string[] values = data.Select(d => d.Value).ToArray();
string[] someOtherValues = data.Select(d => d.SomeOtherValues).ToArray();
Program.IncrementDatabaseRecordsRegistered(data.Count);
DatabaseClass.InsertValues(dateTimes, values, someOtherValues);
}
catch (Exception ex)
{
//log the error
}
}
});
}
Function from DatabaseClass:
public static bool InsertValues(DateTime[] dateTimes, string[] values, string[] someOtherValues)
{
if (!IsConnected())
{
Connect();
}
var rowsInserted = 0;
try
{
using (OracleCommand command = _connection.CreateCommand())
{
command.CommandText =
string.Format(
"Insert into {0} (*****) VALUES (:1, :2, :3)",
_tableName);
command.Parameters.Add(new OracleParameter("1",
OracleDbType.Date,
dateTimes,
ParameterDirection.Input));
command.Parameters.Add(new OracleParameter("2",
OracleDbType.Varchar2,
values,
ParameterDirection.Input));
command.Parameters.Add(new OracleParameter("3",
OracleDbType.Varchar2,
someOtherValues,
ParameterDirection.Input));
command.ArrayBindCount = dateTimes.Length;
rowsInserted = command.ExecuteNonQuery();
}
}
catch (Exception ex)
{
//log the error
}
return rowsInserted != 0;
}
The problem is that after few hours of application working data are still being added to blocking collection but not processed. When I debug it then it does not stop at any breakpoint inside the task. When I check the variable _databaseTask it shows that task is running. The _connection variable shows that database is connected. I added try/catch to the foreach and also in the InsertValues function but it did not help. I made everything static because I firstly thought that this task was collected by GC. But it was not.
Probably the problem is connected with calling database because in my application I have another blocking collection and processing it in a task works without any problems. I do not call there any database function.
Could anyone please help me to find out why the collection is not consumed after few hours?
EDIT: Please do not vote down when you do not understand the question. You lower the possibility that someone who knows the solution sees my question. I did a lot of research on the problem.
Today I notice that probably the thread hangs on line rowsInserted = command.ExecuteNonQuery();
I will try to add the timeout there and also to add transaction.