简体   繁体   English

位图线程安全只读吗?

[英]Is Bitmap threadsafe for readonly?

I got Collection of Bitmap objects. CollectionBitmap对象。 In need to create mutiple Tasks , pass this Collection as argument. 在需要创建多发Tasks ,通过这一Collection的参数。 In task method i will read height/width of each Bitmap , then send this Collection and height/width array to Wcf service. 在任务方法中,我将读取每个Bitmap高度/宽度,然后将此Collection和height / width数组发送到Wcf服务。

So is it threadsafe operation? 那么它是线程安全操作吗? How should i act in this case? 在这种情况下我该怎么办?

It is not, Bitmap doesn't behave much like a "normal" object at all. 并非如此,位图的行为根本不像“正常”对象。 Many operations on a Bitmap object involve an underlying call to Bitmap.LockBits(). 对Bitmap对象的许多操作都涉及对Bitmap.LockBits()的基础调用。 Simple things you'd do, like calling the Save() method or drawing the bitmap with Graphics.DrawImage() or the infamously slow GetPixel() method need to lock the bitmap to get access to a memory-mapped view of the pixel data. 您要做的简单事情,例如调用Save()方法或使用Graphics.DrawImage()绘制位图或臭名昭著的慢速GetPixel()方法,都需要锁定位图才能访问像素数据的内存映射视图。

You may recognize the terminology, the same low-level operating system feature is exposed in the .NET Framework by the MemoryMappedFile class. 您可能会认识到这些术语,.NET Framework中的MemoryMappedFile类公开了相同的低级操作系统功能。 Important for bitmaps, they can contain a huge amount of data. 对于位图很重要,它们可以包含大量数据。 By using an MMF, that pixel data can be kept out of the paging file and page-faulted back into RAM from the image file. 通过使用MMF,可以将像素数据保留在页面文件之外,并从图像文件中将页面数据错误地复制回RAM中。

This has many side-effects, it for example explains the common problem that programmers run into when they discover that the image file is locked and cannot be overwritten. 这有很多副作用,例如,它解释了程序员在发现映像文件已锁定且无法覆盖时遇到的常见问题。 The MMF imposes that lock. MMF施加该锁定。 And a hard constraint is that a bitmap can be locked only once. 硬约束是位图只能锁定一次。 Or in other words, only one non-trivial operation on the Bitmap object can occur at the same time. 换而言之,只能同时对Bitmap对象执行一项重要操作。 Your code is therefore liable to randomly crash when another worker thread tries to do something with the same bitmap object and you don't add the synchronization required to prevent this from happening. 因此,当另一个工作线程尝试使用相同的位图对象执行某项操作时,您的代码可能会随机崩溃,并且您没有添加所需的同步来防止这种情况的发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM