在 UI 线程上获得锁是一种不好的做法吗?例如,我有一个缓存对象,它正在被后台线程和 UI 线程修改。对缓存的任何修改都包含在锁中。伪代码如下:
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;
}
}
}
当 UI 线程调用 RefreshInForegound 时,它必须等待锁定(可能),问题是,这是一种不好的做法,如果是,为什么?
谢谢,-迈克