Trying to update control and getting NullReferenceException

Deadly 提交于 2019-12-25 08:23:02

问题


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

but now i got NullReferenceException at this line:

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

from some reason and i dont know why?

the code:

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

thanks for every one :)


回答1:


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.



来源:https://stackoverflow.com/questions/8205129/trying-to-update-control-and-getting-nullreferenceexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!