BitmapImage
UI スレッドでのみ実行でき、単体テストはバックグラウンド スレッドから実行されます。これが、この例外が発生する理由です。またはその他の UI コンポーネントを含むテストではBitmapImage
、次のことを行う必要があります。
- を使用して UI 作業を UI スレッドにプッシュします。
Dispatcher.BeginInvoke()
- テストを完了する前に、UI スレッドが終了するのを待ちます。
たとえば、ManualResetEvent
(セマフォ) を使用してクロススレッド シグナリングを行い、(キャッチ可能な) 例外がすべてテスト スレッドに戻されるようにします...
[TestMethod]
public void TestMethod1()
{
ManualResetEvent mre = new ManualResetEvent(false);
Exception uiThreadException = null;
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
try
{
BitmapImage bi = new BitmapImage();
// do more stuff
// simulate an exception in the UI thread
// throw new InvalidOperationException("Ha!");
}
catch (Exception e)
{
uiThreadException = e;
}
// signal as complete
mre.Set();
});
// wait at most 1 second for the operation on the UI thread to complete
bool completed = mre.WaitOne(1000);
if (!completed)
{
throw new Exception("UI thread didn't complete in time");
}
// rethrow exception from UI thread
if (uiThreadException != null)
{
throw uiThreadException;
}
}