[問題] 使用ConcurrentDictionary

作者: neocc (neo)   2015-01-17 16:06:05
各位好
小弟想建立一個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 來儲存我螢幕畫面呢?
謝謝
作者: VVll (李奧納多皮卡丘)   2015-01-17 23:20:00
之前用的經驗,ConcurrentDictionary並不是真的thread safe所以還是自己寫lock吧
作者: YahooTaiwan (超可愛南西我老婆)   2015-01-18 04:56:00
http://bit.ly/1wiKv2W這邊有 ConcurrentDictionary 的 source code
作者: neocc (neo)   2015-01-18 21:40:00
我後來發現到是bmp.GetPixel 的關係 無法同時存取

Links booklink

Contact Us: admin [ a t ] ucptt.com