0

AccessViolationException在 WPF 应用程序中感到奇怪。由于堆栈上没有用户代码,我不确定如何解决此问题。它也仅每 2-3 天发生一次,这增加了故障排除的复杂性。

at MS.Win32.PresentationCore.UnsafeNativeMethods+MILUnknown.Release(IntPtr)
at MS.Win32.PresentationCore.UnsafeNativeMethods+MILUnknown.ReleaseInterface(IntPtr ByRef)
at System.Windows.Media.SafeMILHandle.ReleaseHandle()
at System.Windows.Media.Imaging.BitmapSourceSafeMILHandle.ReleaseHandle()
at System.Runtime.InteropServices.SafeHandle.InternalFinalize()
at System.Runtime.InteropServices.SafeHandle.Dispose(Boolean)
at System.Runtime.InteropServices.SafeHandle.Finalize()

我的图像处理代码(略微简化)

private int timerCount;
private void TimerProc() // called from a timer obviously
{
    if(Interlocked.Increment(ref timerCount) !=0)
    {
        Interlocked.Decrement(ref timerCount);
        return;
    }
    try
    {
        byte[] img = FetchImageFromExternalSource(); //returns a jpeg image
        this.Image = LoadImage(new MemoryStream(img));
    }
    finally
    {
        Interlocked.Decrement(ref timerCount);
    }
}

private BitmapImage LoadImage(Stream inputStream)
{
    var bitmapImage = new BitmapImage();
    bitmapImage.BeginInit();
    bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
    bitmapImage.StreamSource = inputStream;
    bitmapImage.EndInit();
    bitmapImage.Freeze();
    return bitmapImage;
}

private BitmapImage image;
public BitmapImage Image
{
    get
    {
        return image;
    }
    set
    {
        if (image!= value)
        {
            this.dispatcher.BeginInvoke(new Action(()=>
            {
                image = value;
                PropertyChanged(this,new PropertyChangedEventArgs("Image"));
            }),null);
        }
    }
}

如果我遇到已知错误(.NET 4)或者我错过的代码是否存在问题,任何建议都将不胜感激。

4

1 回答 1

0

System.Threading.Timer 在后台线程上调用回调,而不是在 UI 线程上调用 BitmapImage 类可能期望的回调。尝试使用DispatcherTimer

于 2013-05-26T21:21:41.523 回答