本文介绍了线程在C#中的位图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
谁能告诉我为什么这个code是错误的,我怎么也得修改,以创建一个简单的位图,其中是存在保证线程安全的访问?
公共静态类ThreadSafe的
{
公共静态只读对象_locker =新的对象();
公共静态位图_snapshot; 公共静态位图快照
{
得到
{
锁(_locker)
{
返回_snapshot;
}
}
组
{
锁(_locker)
{
_snapshot =价值;
}
}
}}
修改我想怎么使用位图:
- 线程A使用位图是这样的:
- Thread B uses the Bitmap in this way:
解决方案
Following the thread safety guidelines from the Bitmap documentation;
...this should be close to the minimum locking implementation;
public static class ThreadSafe
{
private static readonly object BitmapLock = new object();
private static Bitmap _snapshot;
public static Bitmap Snapshot
{
get
{
lock (BitmapLock)
return new Bitmap(_snapshot);
}
set
{
Bitmap oldSnapshot;
Bitmap newSnapshot = new Bitmap(value, new Size(320, 240));
lock (BitmapLock)
{
oldSnapshot = _snapshot;
_snapshot = newSnapshot;
}
if (oldSnapshot != null)
oldSnapshot.Dispose();
}
}
}
这篇关于线程在C#中的位图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!