Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtaining lock on a UI thread

Tags:

c#

Is obtaining a lock on the UI thread a bad practice? For example I have a cache object which is being modified by both background threads and the UI thread. Any modifications to the cache is wrapped inside a lock. The pseudo code is as follows:

 public class Cache
    {
        private readonly Dictionary<string, IEnumerable<string>> _cache;
        private readonly object _onCache = new object();
        public Cache()
        {
            _cache = new Dictionary<string, IEnumerable<string>>();
        }

        //Called by worker threads
        public void RefreshInBackground(IEnumerable<string> items, string key)
        {
            lock (_onCache)
            {
                _cache[key] = items;
            }
        }

        //Called by UI thread.Does this lead to any issues since UI thread is waiting on a lock?
        public void RefreshInForeground(IEnumerable<string> items, string key)
        {
            lock (_onCache)
            {
                _cache[key] = items;
            }
        }
    }

When the RefreshInForegound is called by the UI thread it has to wait on the lock (maybe), and the question is, is this a bad practice and if yes why?

Thanks, -Mike

like image 985
Mike Avatar asked Jan 18 '26 05:01

Mike


1 Answers

If it works fine like it is, I wouldn't change it.

If you have a performance concern then you can tweak it. Some points to improve:

Major

  • Any potentially long-running operation shall be executed in a non-UI thread. Which means you need to remove RefreshInForeground from the class and use Task, ThreadPool, BackgroundWorker etc to run RefreshInBackground from UI.

Minor

  • Switch to Monitor and try-finally, add a timeout. This is still not the best option as UI thread becomes blocked for at most the duration of a timeout. Still better than waiting forever.
  • Use optimized lockers, such as ReaderWriterLockSlim
  • Use ConcurrentDictionary - lockless or non-blocking class
like image 137
oleksii Avatar answered Jan 19 '26 19:01

oleksii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!