[英]What will happen in ConcurrentDictionary if there is a collusion on try add and remove?
In my BL, I want that a certain code will not be executed while another thread is already in progress. 在我的BL中,我希望当另一个线程已经在执行时将不执行某些代码。
The issue is that the code can be executed (by demand) once for each customer but not twice for the same customer 问题在于,每个客户只能(按需)执行一次代码,而同一客户却不能执行两次
I have used the C# ConcurrentDictionary
to keep track of the customers already in progress and when the execution is finished i have removed them from the ConcurrentDictionary
, what will happen if when im trying to remove customer id from the ConcurrentDictionary
while another thread is trying to add (the same or different key)? 我已经使用C#
ConcurrentDictionary
来跟踪已经在进行中的客户,执行完毕后我将它们从ConcurrentDictionary
删除了,如果我试图在另一个线程尝试添加的ConcurrentDictionary
从ConcurrentDictionary
删除客户ID,将会发生什么情况? (相同或不同的密钥)? Is the ConcurrentDictionary
locks for write and the try remove will fail? ConcurrentDictionary
的写锁定和try remove会失败吗?
private static readonly ConcurrentDictionary<int, DateTime> m_customerInProgress = new ConcurrentDictionary<int, DateTime>();
public void ExecuteLogic(int customerId)
{
if (m_customerInProgress.TryAdd(customerId, DateTime.Now) == false)
{
this.Log().Info("customer in progress ");
return;
}
try
{
DoSomething();
}
catch (Exception ex)
{
this.Log().Info("DoSomething failed ");
}
finally
{
DateTime startDateTime;
if (m_customerInProgress.TryRemove(customerId, out startDateTime) == false)
{
this.Log().Fatal("this should never happens");
}
else
{
this.Log().Info("customer finished execution");
}
}
}
Can the this.Log().Fatal("this should never happens");
可以
this.Log().Fatal("this should never happens");
ever happen? 曾经发生过吗?
What will happen if the try add and try remove will execute in the same time for the same key? 如果尝试添加和尝试删除将对同一密钥同时执行,将会发生什么?
What will happen if it will execute for different keys? 如果针对不同的密钥执行,将会发生什么?
Your code is fine. 您的代码很好。 The
TryAdd
will only succeed if the TryRemove
has completed. 该
TryAdd
如果才会成功TryRemove
已完成。
The only odd thing you may see is that after the TryRemove
returns the thread (lets call it T1
) is suspended, and then another thread (lets call that T2
) calls your method. 您可能会看到的唯一奇怪的事情是,在
TryRemove
返回该线程( TryRemove
称为T1
)后,该线程被挂起,然后另一个线程(让其称为T2
)被调用了您的方法。 It may execute the entire method before T1
resumes execution, so your logging could become intertwined. 它可能会在
T1
恢复执行之前执行整个方法,因此您的日志记录可能会交织在一起。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.