I am getting a cross thread invalid exception on a small project with camera capture in windows forms. I am using an async task but can't find the correct way to update a PictureBox element from the task routine without disabling the cross thread exception. What is the correct way to avoid this? I tried the Invoke required logic but then I get the same exception with the MainForm element
private void InitCameraBtn_Click(object sender, EventArgs e)
{
if (InitCameraBtn.Text.Equals("Init Camera"))
{
StartCamera();
InitCameraBtn.Text = "Stop Camera";
isCameraRunning = true;
}
else
{
capture.Release();
InitCameraBtn.Text = "Init Camera";
isCameraRunning = false;
}
}
private async void StartCamera()
{
//cameraThread = new Thread(new ThreadStart(CameraThreadCallback));
//cameraThread.Start();
var r = await CameraThreadCallback();
}
public async Task<int> CameraThreadCallback()
{
return await Task<int>.Run(() =>
{
frame = new Mat();
capture = new VideoCapture(0);
capture.Open(0);
if (capture.IsOpened())
{
while (isCameraRunning)
{
capture.Read(frame);
image = BitmapConverter.ToBitmap(frame);
if (CameraBox.Image != null)
{
CameraBox.Image.Dispose();
}
//CameraBox.Image = image;
setImage(image);
}
}
return 0;
});
}
private void setImage (Bitmap i)
{
//MainForm.CheckForIllegalCrossThreadCalls = false;
CameraBox.Image = i;
Thread.Sleep(500);
}