【发布时间】:2018-11-21 06:54:14
【问题描述】:
我有 .NET Core Web API 解决方案。在每次调用中,我都需要执行一些数据库操作。
问题是一次打开和关闭多个数据库连接。所以为了避免它,我想实现要发送到数据库的对象队列,然后想要一个单独的线程来执行数据库操作。
我尝试了如下代码。但是在这里,消费者线程从不执行分配的功能。 Producer 没有单独的线程,我只是在为队列提供对象。
我应该做哪些修改?需要一些指导,因为我是线程方面的新手。
public static class BlockingQueue
{
public static Queue<WebServiceLogModel> queue;
static BlockingQueue()
{
queue = new Queue<WebServiceLogModel>();
}
public static object Dequeue()
{
lock (queue)
{
while (queue.Count == 0)
{
Monitor.Wait(queue);
}
return queue.Dequeue();
}
}
public static void Enqueue(WebServiceLogModel webServiceLog)
{
lock (queue)
{
queue.Enqueue(webServiceLog);
Monitor.Pulse(queue);
}
}
public static void ConsumerThread(IConfiguration configuration)
{
WebServiceLogModel webServiceLog = (WebServiceLogModel)Dequeue();
webServiceLog.SaveWebServiceLog(configuration);
}
public static void ProducerThread(WebServiceLogModel webServiceLog)
{
Enqueue(webServiceLog);
Thread.Sleep(100);
}
}
我在 StartUp.cs 中创建并启动了线程:
public Startup(IConfiguration configuration)
{
Thread t = new Thread(() => BlockingQueue.ConsumerThread(configuration));
t.Start();
}
在 Controller 中,我编写了代码来提供队列:
[HttpGet]
[Route("abc")]
public IActionResult GetData()
{
BlockingQueue.ProducerThread(logModel);
return StatusCode(HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound, ApplicationConstants.Message.NoBatchHistoryInfo);
}
【问题讨论】:
-
"问题是一次打开和关闭多个数据库连接。所以要避免它"你为什么要这样做,你有并发问题吗?
-
是的。我面临的并发问题。有什么建议吗?
-
那我也去看看TPL,如果有帮助的话。
-
两个建议,首先不要将您用作锁的对象公开。要确保在不让其他对象加入聚会的情况下不会使某些东西陷入僵局,这已经够难的了。其次,看一下 BlockingCollection,它为您实现了生产者消费者模式。
-
我听说过阻止收集。我会检查它是否对我有帮助。谢谢。
标签: c# multithreading .net-core queue thread-synchronization