Here I am using multi threading and linq to sql.
Here I upload my code snippet:
public class PostService
{
MessageRepository objFbPostRespository = new MessageRepository();
public void callthreads()
{
for (int i = 0; i < 100; i++)
{
Thread th = new Thread(postingProcess);
th.Start();
}
}
public void postingProcess()
{
objFbPostRespository.AddLog("Test Multithread", DateTime.Now);
}
}
Message Repository class
class MessageRepository
{
DataClassesDataContext db_Context = new DataClassesDataContext();
public void AddLog(string Message, DateTime CurrentDateTime)
{
FbMessgaeLog FbMessage = new FbMessgaeLog
{
Message = Message,
Time = CurrentDateTime
};
db_Context.FbMessgaeLogs.InsertOnSubmit(FbMessage);
db_Context.SubmitChanges();
}
}
When I run it without threads then it's work fine after include thread I was got following error msg:
Error: An item with the same key has already been added.
Thanks in advance...:)
You cannot use a LINQ DataContext in concurrent fashion:
Any instance members are not guaranteed to be thread safe.
Therefore you need to either serialize access (lock) which will be horribly inefficient, or better use a separate context in each thread:
public class PostService
{
public void callthreads()
{
for (int i = 0; i < 100; i++)
{
Thread th = new Thread(postingProcess);
th.Start();
}
}
public void postingProcess()
{
using (MessageRepository objFbPostRespository = new MessageRepository())
{
objFbPostRespository.AddLog("Test Multithread", DateTime.Now);
}
}
}
I also hope, for your own sake, that your test has actual logic to wait for the test threads to complete before shutting down... And, of course, properly implement IDisposable in your repository and dispose the context so that the DB connection get placed back in the pool.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With