Tag: thread safety

Async threadsafe从MemoryCache获取

我创建了一个使用.NET MemoryCache的异步缓存。 这是代码 public async Task GetAsync(string key, Func<Task> populator, TimeSpan expire, object parameters) { if(parameters != null) key += JsonConvert.SerializeObject(parameters); if(!_cache.Contains(key)) { var data = await populator(); lock(_cache) { if(!_cache.Contains(key)) //Check again but locked this time _cache.Add(key, data, DateTimeOffset.Now.Add(expire)); } } return (T)_cache.Get(key); } 我认为唯一的缺点是我需要在锁外等待,所以populator不是线程安全的,但是因为await不能驻留在锁内,我想这是最好的方法。 我错过了任何陷阱吗? 更新 :当antoher线程使缓存无效时,Esers应答的版本也是线程安全的 public async Task GetAsync(string key, Func<Task> […]

是int吗? 线程安全?

我知道.Net中的所有32位类型(例如, int , bool等)都是线程安全的。 也就是说,不会有部分写入(根据规范)。 但是,这同样适用于int? (可以为空)?

将线程安全访问方法写入Windows窗体控件的最短方法

在这篇文章中: http://msdn.microsoft.com/en-us/library/ms171728(VS.80).aspx 作者使用以下方法对Windows窗体控件进行线程安全调用: private void SetText(string text) { // InvokeRequired required compares the thread ID of the // calling thread to the thread ID of the creating thread. // If these threads are different, it returns true. if (this.textBox1.InvokeRequired) { SetTextCallback d = new SetTextCallback(SetText); this.Invoke(d, new object[] { text }); } else { this.textBox1.Text […]

如何使ObservableCollection线程安全?

System.InvalidOperationException: Collection was modified; enumeration operation may not execute. 我正在添加/删除不在UI线程上的ObservableCollection。 我有一个方法名称EnqueueReport添加到colleciton和DequeueReport从集合中删除。 步骤流程如下: – 1.call EnqueueReport每当请求新报告时 每隔几秒调用一次方法来检查是否生成了报告(这有一个foreach循环,用于检查ObservableCollection中所有报告的生成状态) 如果生成报告,则调用DequeueReport 我在C#库中并不多。 有人可以指导我吗?

事件处理程序不是线程安全吗?

所以我已经阅读过,而不是直接调用事件 if (SomeEvent != null) SomeEvent(this, null); 我应该这样做 SomeEventHandler temp = SomeEvent; if (temp != null) temp(this, null); 为什么会这样? 第二个版本如何变得线程安全? 什么是最佳做法?