Thread Synchronization Issue in a Multithreaded Environment using Entoty Framework
-
Friday, May 11, 2012 5:29 AM
Hi Experts,
I have developed a tool for RSS Data Collection which is Multithreaded the number of Threads being configurable. However I am facing an issue where I have to set the Count of the so far processed Items in an Activity Logger made in Entity Framework....The problem is the Count is never Updated properly in Multithreading environment which other wise works fine for a single Thread...Now the Tool has to use the Multithtreading with a minimum of 5 threads running but I am just unable to synchronize the Threads although used autoResetEvents,etc.. I am just out of ideas at this point...below is the method in activityLogegr I use to call from my Tool
public void SetCurrentValue(string currentValue)
private void LogToDB(string currentValue)
{
try
{
currentCount++;
this.currentValue = currentValue;
if (currentCount >= RecordSize)
{
LogToDB(currentValue);
currentCount = 0;
}
}
catch (Exception ex)
{
IntranetLogger.LogError("Failed to execute SetCurrentValue",ex);
}
}
{
try
{
if (string.IsNullOrEmpty(currentValue)) return;
using (LoggingEntities entityContainer = new LoggingEntities(entityConnection))
{
ActivityLog log = (from e in entityContainer.ActivityLogs
where e.ID == LogId
select e).FirstOrDefault();
log.CurrentValue = currentValue;
entityContainer.SaveChanges();
}
}
catch (Exception ex)
{
IntranetLogger.LogError("Failed to execute LogToDB Method",ex);
}
}Please help..
Regards,
nilamazing
All Replies
-
Wednesday, May 23, 2012 11:35 AM
The issue you are having is how the variable "currentCount++" is being declared. In a multithread environment you have to make sure you are declaring the variable as "public static" for all the threads to see the variable and it has to be in the same namespace as the thread running. You also have to make sure that you aren't generating a "new class" for everty thread in the class where currentcount is being declared. A "public static" variable force a variable to be placed in global memory space when the code gets compiled. even if it is in global memory it is still protected and only allows read/write of the variable to the class (and children) that owns the variable. if your multithread is creating siblings and the variable is declared in one sibling then other siblings won't have access to the variable.
jdweng

