Possible Duplicate:
How to stop BackgroundWorker on Form’s Closing event?
**Regarding possible duplicate - BackgroundWorker methods are not applicable here.
Below is my attempt to use AForge library to receive video from IP cameras.
Each video stream is supposed to run in separate thread, notifying UI thread when new frame arrives. Event handler is executed in the same thread, that raised it, so I need to use Invoke.
All runs smoothly until I wish to stop the application. The line marked with '>>>' throws ObjectDisposed exception, so my application doesn't end as smoothly as it runs.
I know problem is with understanding multithreading, just can't see the real problem because of it. Could someone please explain what happens here?
Form1.cs
public void generic_NewFrame(object sender, NewFrameEventArgs e)
{
...
if (pictureBox1.InvokeRequired)
{
>>> pictureBox1.Invoke(new MethodInvoker(delegate()
{
pictureBox1.BackgroundImage = (Image)buf;
}));
}
else
{
pictureBox1.BackgroundImage = (Image)buf;
}
...
}
As short as possible, Camera class:
Camera.cs
//Camera thread loop
private void WorkerThread()
{
while (!stopEvent.WaitOne(0, false))
{
...
if (!stopEvent.WaitOne(0, false))
{
// notify UI thread
OnNewFrame(new NewFrameEventArgs(Last_frame));
...
}
}
override public void Play()
{
stopEvent = new ManualResetEvent(false);
thread = new Thread(new ThreadStart(WorkerThread));
thread.Start();
}
override public void Stop()
{
if (thread != null)
{
stopEvent.Set();
}
}