gpt4 book ai didi

sql-server - 使用多线程时在数据库中插入行?

转载 作者:行者123 更新时间:2023-12-02 20:53:16 24 4
gpt4 key购买 nike

这里我使用多线程和 linq to sql。

这里我上传我的代码片段:

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);
}
}

消息存储库类

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();
}
}

当我在没有线程的情况下运行它时,在包含线程后它工作正常,我收到以下错误消息:

错误:已添加具有相同 key 的项目。

提前致谢...:)

最佳答案

您不能使用 LINQ DataContext以并发方式:

Any instance members are not guaranteed to be thread safe.

因此,您需要序列化访问(锁定),这将非常低效,或者更好地在每个线程中使用单独的上下文:

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);
}
}
}

为了您自己的利益,我还希望您的测试具有实际的逻辑来等待测试线程在关闭之前完成...当然,在您的存储库中正确实现 IDisposable 并处置上下文,以便数据库连接被放回池中。

关于sql-server - 使用多线程时在数据库中插入行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5677144/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com