logo
down
shadow

Dictionary of lock object in order to reduce latency in C#?


Dictionary of lock object in order to reduce latency in C#?

By : Uollano
Date : November 21 2020, 01:01 AM
I wish this help you ConcurrentDictonary has tools to help you do the situation you are in, if you switch your retrieval/creation of your existing list to a single thread safe operation it makes the problem much simpler.
code :
public static void SaveLaterMessages(MSG msg)
{
    var dic = Globals.DIC_PROFILEID__MSGS;

    List<MSG> existingLst = dic.GetOrAdd(msg.To, (key) => new List<MSG>());

    lock(((ICollection)existingLst).SyncRoot)
    {
        existingLst.Add(msg);
    }
}
public static void SaveLaterMessages(MSG msg)
{
    var dic = Globals.DIC_PROFILEID__MSGS;

    List<MSG> existingLst = dic.GetOrAdd(msg.To, (key) => new List<MSG>());

    var lockingObj = GetLockingObject(existingLst);
    lockingObj.EnterWriteLock();
    try
    {
        existingLst.Add(msg);
    }
    finally
    {
        lockingObj.ExitWriteLock();
    }
}

private static ConcurrentDictionary<List<MSG>, ReaderWriterLockSlim> _msgLocks = new ConcurrentDictionary<List<MSG>, ReaderWriterLockSlim>();

public static ReaderWriterLockSlim GetLockingObject(List<MSG> msgList)
{
    _msgLocks.GetOrAdd(msgList, (key) => new ReaderWriterLockSlim());
}


//Elsewhere in multiple threads.

public MSG PeekNewestMessage(int myId)
{
    var dic = Globals.DIC_PROFILEID__MSGS;
    var list = dic[myId];
    var lockingObj = GetLockingObject(list);

    lockingObj.EnterReadLock();
    try
    {
        return list.FirstOrDefault();
    }
    finally
    {
        lockingObj.ExitReadLock();
    }
}


Share : facebook icon twitter icon
Using lock on the key of a Dictionary<string, object>

Using lock on the key of a Dictionary<string, object>


By : markus
Date : March 29 2020, 07:55 AM
around this issue Locking on an object that is accessible outside of the code locking it is a big risk. If any other code (anywhere) ever locks that object you could be in for some deadlocks that are hard to debug. Also note that you lock the object, not the reference, so if I gave you a dictionary, I may still hold references to the keys and lock on them - causing us to lock on the same object.
If you completely encapsulate the dictionary, and generate the keys yourself (they aren't ever passed in, then you may be safe.
code :
public class Something
{
  private readonly object lockObj = new object();

  public SomethingReentrant()
  {
    lock(lockObj)    // Line A
    {
      // ...
     }
   }
}
  lock(this)
Correct way to lock the dictionary object

Correct way to lock the dictionary object


By : VestigoDan
Date : March 29 2020, 07:55 AM
Does that help With Dictionary<,> you have to lock both reading and writing. So both
code :
lock( ConnectionList ) {
   ConnectionList.Add( key, res );
}
lock( ConnectionList ) {
   res = ConnectionList[ key ];
}
lock( ConnectionList ) {
   int cnt = ConnectionList.Count;
}
lock( ConnectionList ) {
   ConnectionList.Clear();
}
lock( ConnectionList ) {
   foreach ( var kv in ConnectionList ) {
      // Do things
   }
}
How to reduce connection latency with AWS SQS?

How to reduce connection latency with AWS SQS?


By : Carlos Mascarua
Date : March 29 2020, 07:55 AM
will be helpful for those in need SQS has shown very low latency during our usage. However, our logic runs on EC2 instances.
Most likely, there is significant latency between your servers and SQS. Either use SQS in a region physically closer to your servers or move your application's logic onto EC2 or Lambda.
Python - convert list into dictionary in order to reduce complexity

Python - convert list into dictionary in order to reduce complexity


By : jecowa
Date : March 29 2020, 07:55 AM
To fix the issue you can do The code from the question does just one thing: fills all words from a file into a list. The complexity of that is O(n).
Filling the same words into any other type of container will still have at least O(n) complexity, because it has to read all of the words from the file and it has to put all of the words into the container.
code :
word_dict = dict((elt, 1) for elt in word_list) 
set_of_words = {elt.strip() for elt in open("bible_words.txt", "r").readlines()}
>>> timeit.timeit('[n for n in range(1000000)]', number=10)
0.7802875302271843
>>> timeit.timeit('{n for n in range(1000000)}', number=10)
1.025623542189976
>>> timeit.timeit('989234 in values', setup='values=[n for n in range(1000000)]', number=10)
0.19846207875508526
>>> timeit.timeit('989234 in values', setup='values={n for n in range(1000000)}', number=10)
3.5699193290383846e-06
How to reduce latency while using Dialogflow API?

How to reduce latency while using Dialogflow API?


By : user3195843
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , Have you tried another connection? E.g. mobile hotspot?
So you can find out if it is some issue with your network.
code :
start = time.time()
detect_intent_texts(
print("recognition took: " + str(time.time() - start)[:5])
for text in texts:
    start = time.time()
    [...]
    print("querytook: " + str(time.time() - start)[:5])
Related Posts Related Posts :
  • Stop Continuation Task upon exception thrown from parent task
  • Is there a way to make msbuild write error output to stderr?
  • Unit testing: TDD with POCO Objects with navigation properties (relationship fixup)
  • GridSplitter disables my RowDefinition style
  • Memory leak only in Release mode
  • how to read specified string from url
  • how to store html code EMail template in a string variable or textbox c#
  • Set Selected Date to TimePicker wpf (TimePickers inside DataTemplate)
  • How to draw line in Silverlight Specifying Height?
  • Stored procedure executes but does not update data
  • ASP.NET ListBox Trouble
  • Why does C# also not allow empty conditions in while loops?
  • Unable to get a block of code into my regex match groups
  • What is difference between dbcontext.Add and dbcontext.AddObject
  • How do I update the file version number of C# DLL without recompiling?
  • Value for html control always null
  • HttpClient hangs when timeout is setting (Windows Phone)
  • Handle Multiple Form tag in asp.net page?
  • create word document with html content in c#
  • Confusion about Find And Replace
  • Format sms messages in Clickatell
  • Automated Function Overload
  • String to date in MS Access SQL statement gives type mismatch error
  • ShowDialog exiting on certain events
  • Is there a try Convert.ToInt32... avoiding exceptions
  • How to move wpf application into minimize tray at Window Start-up C#?
  • How to change display format of long variable?
  • How to use Addfields in MongoDB C# Aggregation Pipeline
  • MsTest TestCleanup method not called when an unhandled exception is thrown
  • missing last data when exporting gridview to excel
  • How to add array of objects to List in c#
  • Lambda Expression to order (sort) my list collection
  • Library for displaying music notation
  • How to compare two dictionaries in c# and get the output as True and False after validation
  • specify fields to be serialized with JSON
  • How do you obtain the content of a specific node using XmlDocument in C#?
  • How to ignore the first line in a csv file when you read the csv file in C#
  • c# - Problem calling public void from class
  • How to tell a class which objects it should create? Type vs. object confusion :(
  • Save CheckBox state to xml
  • WIX CAQuietExec NETSH Command Fails
  • Issues sending http put request every 60 seconds to RoR app
  • ConfigurationManager.ConnectionStrings.ConnectionString Issue
  • Real size WPF controls for printing
  • How to cancel properly?
  • C# String multiplication error
  • Using Solrnet and Assigning Attributes with Entity Framework Generated POCOs
  • Regex pattern for single backslash
  • TextBox: insert spaces for credit card number?
  • C# DLL loaded for exe-application is not found when launching similar DLL by rundll32.exe
  • Debug a Windows Service with WCF library
  • Open a file from an external assembly?
  • Servicestack RegistrationFeature Unable to bind request
  • Index was outside the bounds of the array confusion
  • Error in Xml to List code. The ':' character, hexadecimal value 0x3A, cannot be included in a name
  • I am trying to do a while loop with a string conditional statement in C#
  • C# 'Cannot access a disposed object. Object name: 'SslStream'.'
  • How to make Gecko use seperate CookieContainer per instance?
  • C# Advanced form "please wait"
  • Send and Receive data C# using network stream
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org