Eliav ran
Eliav ran

Reputation: 53

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.

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)? Is the ConcurrentDictionary locks for write and the try remove will fail?

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"); 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?

Upvotes: 2

Views: 641

Answers (1)

Sean
Sean

Reputation: 62492

Your code is fine. The TryAdd will only succeed if the TryRemove has completed.

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. It may execute the entire method before T1 resumes execution, so your logging could become intertwined.

Upvotes: 4

Related Questions