好的,我想我也会把我自己的答案放在这里,因为它从不同的角度展示了事物。Justin Angel 的回答还可以,但有几个问题:
- 当代码深入模型层并在后台线程上运行时,不可能有对 Dispatcher 的引用。
- 我需要从该方法返回缩略图,稍后在相同的同步上下文中使用它。否则,我将不得不围绕这种创建缩略图的方法更改大量代码。
考虑到这个要求,这是我的解决方案:
private WriteableBitmap CreateThumbnail(Stream stream, int width, int height, SynchronizationContext uiThread)
{
// This hack comes from the problem that classes like BitmapImage, WritableBitmap, Image used here could
// only be created or accessed from the UI thread. And now this code called from the threadpool. To avoid
// cross-thread access exceptions, I dispatch the code back to the UI thread, waiting for it to complete
// using the Monitor and a lock object, and then return the value from the method. Quite hacky, but the only
// way to make this work currently. It's quite stupid that MS didn't provide any classes to do image
// processing on the non-UI threads.
WriteableBitmap result = null;
var waitHandle = new object();
lock (waitHandle)
{
uiThread.Post(_ =>
{
lock (waitHandle)
{
var bi = new BitmapImage();
bi.SetSource(stream);
int w, h;
double ws = (double)width / bi.PixelWidth;
double hs = (double)height / bi.PixelHeight;
double scale = (ws > hs) ? ws : hs;
w = (int)(bi.PixelWidth * scale);
h = (int)(bi.PixelHeight * scale);
var im = new Image();
im.Stretch = Stretch.UniformToFill;
im.Source = bi;
result = new WriteableBitmap(width, height);
var tr = new CompositeTransform();
tr.CenterX = (ws > hs) ? 0 : (width - w) / 2;
tr.CenterY = (ws < hs) ? 0 : (height - h) / 2;
tr.ScaleX = scale;
tr.ScaleY = scale;
result.Render(im, tr);
result.Invalidate();
Monitor.Pulse(waitHandle);
}
}, null);
Monitor.Wait(waitHandle);
}
return result;
}
我仍在 UI 线程中(在视图模型中)捕获 UI 线程的 SynchronizationContext,并进一步传递它,然后我使用闭包来捕获局部变量,以便它们可用于运行的回调在 UI 线程上。我还使用 lock 和 Monitor 来同步这两个线程并等待图像准备好。
如果有的话,我会根据投票接受我或 Justin Angel 的回答。:)
编辑:当您在 UI 线程上时(例如,在按钮单击处理程序中),您可以获得 Dispatcher 的实例SynchronizationContext
。System.Threading.SynchronizationContext.Current
像这样:
private async void CreateThumbnailButton_Clicked(object sender, EventArgs args)
{
SynchronizationContext uiThread = SynchronizationContext.Current;
var result = await Task.Factory.StartNew<WriteableBitmap>(() =>
{
Stream img = GetOriginalImage();// get the original image through a long synchronous operation
return CreateThumbnail(img, 163, 163, uiThread);
});
await SaveThumbnailAsync(result);
}