Skip to content

Commit 44dcbb4

Browse files
committed
Binary Thread Safety
1 parent 09e572f commit 44dcbb4

1 file changed

Lines changed: 15 additions & 8 deletions

File tree

  • IronSoftware.Drawing/IronSoftware.Drawing.Common

IronSoftware.Drawing/IronSoftware.Drawing.Common/AnyBitmap.cs

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ public partial class AnyBitmap : IDisposable, IAnyImage
5757
/// </summary>
5858
private Lazy<IEnumerable<Image>> _lazyImage { get; set; }
5959

60+
private readonly object _binaryLock = new object();
6061
private byte[] _binary;
6162

6263
/// <summary>
@@ -70,18 +71,24 @@ private byte[] Binary
7071
if (_binary == null)
7172
{
7273
///In case like <see cref="AnyBitmap(Image)"/> Binary will be assign once the image is loaded
73-
var _ = _lazyImage?.Value; //force load
74+
var _ = _lazyImage?.Value; //force load but _binary can still be null depended on how _lazyImage was loaded
7475
}
7576

76-
if (IsDirty == true || _binary == null)
77+
if (_binary == null || IsDirty)
7778
{
78-
//Which mean we need to update _binary to sync with the image
79-
using var stream = new MemoryStream();
80-
IImageEncoder enc = GetDefaultImageExportEncoder();
79+
lock (_binaryLock)
80+
{
81+
if (_binary == null || IsDirty)
82+
{
83+
//Which mean we need to update _binary to sync with the image
84+
using var stream = new MemoryStream();
85+
IImageEncoder enc = GetDefaultImageExportEncoder();
8186

82-
_lazyImage.Value.First().Save(stream, enc);
83-
_binary = stream.ToArray();
84-
IsDirty = false;
87+
_lazyImage.Value.First().Save(stream, enc);
88+
_binary = stream.ToArray();
89+
IsDirty = false;
90+
}
91+
}
8592
}
8693

8794
return _binary;

0 commit comments

Comments
 (0)