尝试更新控件并获取NullReferenceException

时间:2011-11-20 22:07:47

标签: wpf wpf-controls nullreferenceexception

我得到了与我的迷你项目有关的最后一个问题的答案:当我试图从其他线程更新图像控制时,我得到了错误: Trying to update image control source from other tread and getting Error- enter link description here

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

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

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

代码:

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();
    }
}

感谢每一个人:)

1 个答案:

答案 0 :(得分:0)

我相信在使用(...)语句结束之前返回值不会丢弃一次性,也会导致问题,我不确定它是如何反映这种想法的。