看板 C_Sharp 關於我們 聯絡資訊
各位好 小弟想建立一個2D的 ConcurrentDictionary 來儲存現在螢幕的畫面 並且我用Parallel.For 來給value Code如下所示 public ConcurrentDictionary<int, ConcurrentDictionary<int,Color>> pub_screen_all_dic = new ConcurrentDictionary<int, ConcurrentDictionary<int,Color>>();//記錄所有像素 #region 建立一個1920x1080的2D ConcurrentDictionary for(int x=0;x<exact_from_rect.Width;x++) { for (int y = 0; y < exact_from_rect.Height; y++) { if (!pub_screen_all_dic.ContainsKey(x)) { ConcurrentDictionary<int, Color> A = new ConcurrentDictionary<int, Color>(); pub_screen_all_dic.TryAdd(x, A); } if (!pub_screen_all_dic[x].ContainsKey(y)) { Color B = new Color(); pub_screen_all_dic[x].TryAdd(y, B); } pub_screen_all_dic[x].TryAdd(y, Color.Blue); } } #endregion Point upperLeftSouce = new Point(0, 0); Bitmap bmp = new Bitmap(1920, 1080); using (Graphics g = Graphics.FromImage(bmp)) { g.CopyFromScreen(upperLeftSouce, new Point(0, 0), bmp.Size); } Parallel.For(0, blockRegionSize.Width, x => { Parallel.For(0, blockRegionSize.Height, y => { pub_screen_all_dic[x].TryAdd(y, bmp.GetPixel(x, y)); }); }); pub_screen_all_dic[x].TryAdd(y, bmp.GetPixel(x, y)); 會出現問題 其他地方正在使用物件。 請問我要怎麼寫才可以達到用multithread 來儲存我螢幕畫面呢? 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 219.71.212.90 ※ 文章網址: https://www.ptt.cc/bbs/C_Sharp/M.1421482359.A.225.html
VVll: 之前用的經驗,ConcurrentDictionary並不是真的thread safe 01/17 23:20
VVll: 所以還是自己寫lock吧 01/17 23:21
YahooTaiwan: http://bit.ly/1wiKv2W 01/18 04:56
YahooTaiwan: 這邊有 ConcurrentDictionary 的 source code 01/18 04:56
neocc: 我後來發現到是bmp.GetPixel 的關係 無法同時存取 01/18 21:40