[问题] 使用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