WriteableBitmap hangs when source bitmap is rendered on other thread
- Dominant language
- C#
- Stars
- 7.7k
- Forks
- 1.3k
- Avg merge
- 1d 11h
- Merged PRs (30d)
- 61
Description
* .NET Core Version: 5.0.201
* Windows version: Windows 10x64 20H2 19042.906
* Does the bug reproduce also in WPF for .NET Framework 4.8?
I'm not able to test: [.NET Framework 4.8 not available in VS 2019 New Project wizard](https://developercommunity.visualstudio.com/t/NET-Framework-48-not-listed-in-New-Pro/1395034?entry=myfeedback&space=8&scope=follow&sort=newest)
However, I can reproduce in .NET Framework 4.72.
* Is this bug related specifically to tooling in Visual Studio (e.g. XAML Designer, Code editing, etc...)? No.
### Problem description:
[`WriteableBitmap`](https://docs.microsoft.com/dotnet/api/system.windows.media.imaging.writeablebitmap) isn't thread safe.
Creating a `WriteableBitmap` from a bitmap that's assigned to an [`Image`](https://docs.microsoft.com/dotnet/api/system.windows.controls.image) control will hang the UI thread when the UI thread is busy rendering the image.
### Actual behavior:
The WPF application will hang unexpectedly and randomly.
### Expected behavior:
The WPF application should not hang.
### Minimal repro:
https://github.com/SetTrend/BitmapSourceTest
```c#
private void ProcessImageAsync(string filePath)
{
TransformedBitmap tb = new TransformedBitmap(new BitmapImage(new Uri(filePath)), new RotateTransform(90));
CopyBitmapSourceToUi(tb);
_ = new WriteableBitmap(tb);
}
private void CopyBitmapSourceToUi(BitmapSource image)
{
BitmapSource uiSource;
uiSource = BitmapFrame.Create(image);
uiSource.Freeze(); // locks the bitmap source, so other threads can access
Dispatcher.Invoke(() => origImage.Source = uiSource);
//Thread.Sleep(10); // WPF needs time to render the bitmap. During this period, creating a WriteableBitmap makes the program hang.
}
```
Contributor guide
Assessment
This issue has not been assessed yet.