iT邦幫忙

0

,Net Core Singleton Thread Safe 問題

  • 分享至 

  • xImage

因在 webapi 內使用一個 Model 來存放共用資料像是下面這樣

public class ViewModel
{
    public Dictionary<int, Dictionary<string, ItemModel>> data = new Dictionary<int, Dictionary<string, ItemModel>>();
}

並使用 service.AddSingleton() 做DI
但是在實際使用時
似乎會產生 Thread-Unsafe 的狀態
導致機率性的收到 0 筆的回傳
請問這部分需要如何做更改
才能在不同 service 做 add KeyValuePair,
並隨時可以抓取正確資料回傳
感謝

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

6
暐翰
iT邦大師 1 級 ‧ 2020-11-10 08:31:54

換用 ConcurrentDictionary<TKey,TValue>
目前 Dapper 也是使用這個做到 muti-thread safe

我要發表回答

立即登入回答