Hi @דני שטרית , Welcome to Microsoft Q&A,
It seems like you're using a ConcurrentDictionary to store the route statuses, which is already designed to be thread-safe for individual operations. However, in your code, you still use a lock (_syncObject) when accessing and modifying the dictionary. If you want to take full advantage of the thread-safety provided by ConcurrentDictionary, you can remove the locks from the GetRouteStatus and UpdateStatus methods. Try to use the code bellow:
using AutomationService.Shared.Helpers;
using System.Collections.Concurrent;
namespace AutomationClient.Shared.Helpers
{
public class RoutesStatusSingleton
{
private static RoutesStatusSingleton _routesStatus;
private static ConcurrentDictionary<string, bool> _dic = new ConcurrentDictionary<string, bool>();
private RoutesStatusSingleton()
{
}
public static RoutesStatusSingleton GetInstance()
{
if (_routesStatus == null)
{
lock (_syncObject)
{
if (_routesStatus == null)
{
_routesStatus = new RoutesStatusSingleton();
}
}
}
return _routesStatus;
}
public bool GetRouteStatus(string routeName)
{
if (_dic.TryGetValue(routeName, out bool isRunning))
{
if (!isRunning)
{
if (_dic.TryRemove(routeName, out bool oldStatus))
{
_dic.TryAdd(routeName, true);
MongoDbHelper.InsertRouteActivationDocument(routeName, true.ToString());
return false; // start first time to run
}
else
{
return false; // case of failure at if
}
}
else
{
return true; // is running
}
}
else // case of failure at if
{
_dic.TryAdd(routeName, true);
MongoDbHelper.InsertRouteActivationDocument(routeName, true.ToString());
return false;
}
}
public bool UpdateStatus(string routeName, bool newStatus)
{
if (_dic.TryRemove(routeName, out bool oldStatus))
{
MongoDbHelper.InsertRouteActivationDocument(routeName, newStatus.ToString());
return _dic.TryAdd(routeName, newStatus);
}
else
{
return false;
}
}
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.