在我的应用程序中,我有一个在后台运行的任务来执行一项长时间运行的工作。用户可以通过单击停止按钮随时取消作业。实现如下:
private CancellationTokenSource m_tokenSource;
private void onStop()
{
m_tokenSource.Cancel();
}
private void onStart()
{
m_tokenSource = new CancellationTokenSource();
AsyncDoingJob();
}
private async void AsyncDoingJob()
{
await Task.Run(() =>
{
for (int imgIdx = 0; imgIdx < m_ListImageFiles.Count; imgIdx++)
{
if (m_tokenSource.IsCancellationRequested) // Check if the user clicks Stop button
{
return;
}
byte[] imageData = File.ReadAllBytes(m_ListImageFiles[imgIdx]); // Load image in background
Application.Current.Dispatcher.Invoke(() =>
{
m_model.Image = CreateImage(imageData);
m_model.Image.Freeze();
MyImage = m_model.Image; // This calls NotifyPropertyChanged() to update the image on GUI
}
// Access to m_model.Image for some reason
}
}, m_tokenSource.Token);
}
问题:有时,在执行作业时,GUI 停止更新(挂起)。如果我尝试操作 GUI,则会发生异常: System.Runtime.InteropServices.COMException: UCEERR_RENDERTHREADFAILURE (Exception from HRESULT: 0x88980406)
我在这里发现了一个类似的问题: WPF render thread failures
你知道它是什么以及如何解决这个问题吗?我的源代码有什么问题吗?