я получил ответ на мою последнюю проблему, связанную с моим мини-проектом: при попытке обновить управление изображением из другого потока я получил ошибку:
Попытка обновить источник управления изображением с другого протектора и получение ошибки - введите описание ссылки здесь
но теперь я получил 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();
}
}
спасибо за каждого :)