尝试更新控件并获取 NullReferenceException [英] Trying to update control and getting NullReferenceException

查看:49
本文介绍了尝试更新控件并获取 NullReferenceException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了与我的迷你项目相关的最后一个问题的答案:当我尝试从其他线程更新图像控件时,出现错误:尝试从其他更新图像控件源踩踏并获取错误-在此处输入链接描述

i got answer to my last problem related to my mini project: when i tried to update image control from other thread i got error: Trying to update image control source from other tread and getting Error- enter link description here

但现在我在这一行得到了 NullReferenceException:

but now i got NullReferenceException at this line:

item.Dispatcher.Invoke(new Action(() => image1.Source = item));

出于某种原因,我不知道为什么?

from some reason and i dont know why?

代码:

public partial class MainWindow : Window
{
    BlockingCollection<BitmapSource> pictures = new BlockingCollection<BitmapSource>();

    public MainWindow()
    {
        InitializeComponent();

        ScreenCapture sc = new ScreenCapture();
        System.Drawing.Image source = sc.CaptureScreen();
        System.Windows.Media.ImageSource img = ToWpfBitmap(source);
        this.image1.Source = img; 
    }

    public BitmapSource ToWpfBitmap(System.Drawing.Image bitmap)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);

            stream.Position = 0;
            BitmapImage result = new BitmapImage();
            result.BeginInit();
            result.CacheOption = BitmapCacheOption.OnLoad;
            result.StreamSource = stream;
            result.EndInit();
            result.Freeze();
            return result;
        }
    }

    private void TakeScreenshot()
    {
        while (true)
        {        
            ScreenCapture sc = new ScreenCapture();
            System.Drawing.Image img = sc.CaptureScreen();
            pictures.Add(ToWpfBitmap(img));           
        }   
    }

    private void UpdateScreen()
    {
        while (true)
        {
            if (pictures.Count > 10)
            {
                var item = pictures.Take(); // blocks if count == 0
                item.Dispatcher.Invoke(new Action(() => image1.Source = item));
            }
        }
    }

    private void MenuItem_Click(object sender, RoutedEventArgs e)
    {
        var takeScreen = new Timer(o => TakeScreenshot(), null, 0, 10);
        new Thread(new ThreadStart(TakeScreenshot)).Start();
        new Thread(new ThreadStart(UpdateScreen)).Start();
    }
}

感谢每一位:)

推荐答案

我相信在 Using(...) 语句完成之前返回值不会处理一次性的,并且也会导致问题,我不确定它是如何反映这一点的想.

I believe returning value before Using(...) statement finishes doesn't dispose disposable, and can cause problems too, i am not sure how it reflects this thought.

这篇关于尝试更新控件并获取 NullReferenceException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆