I'm using DirectShowLib-2005 for my C#/WPF project. When camera starts, I run media control:
m_FilterGraph = new FilterGraph() as IFilterGraph2;
/* Initializations */
IMediaControl mediaCtrl = m_FilterGraph as IMediaControl;
hr = mediaCtrl.Run();
DsError.ThrowExceptionForHR(hr);
Application Runs, camera works good. But sometimes (not always) when I quit the application freeze. I paused the debugger and I saw that the application is stop on the following line:
if (m_FilterGraph != null)
{
IMediaControl mediaCtrl = m_FilterGraph as IMediaControl;
mediaCtrl.Stop(); // <= *** Blocked here ***
Marshal.ReleaseComObject(m_FilterGraph);
m_FilterGraph = null;
}
How can I prevent this freeze ? Can I add a time out or try/catch ?
You will find around, if you look for it, a number of conversations discussing similar symptoms of freeze in attempt to stop streaming.
Implementation of IMediaControl.Stop
alone is fine as well as code snippets posted. Important is that streaming is multi-threaded and the call involves synchronization with streaming thread: signaling it to stop and waiting for completion; also this involves stopping of all participating filters. A problem with threading, any of the filters or - pretty often - even a callback from a filter to controlling code carelessly ignoring threading concepts might cause a deadlock.
Your description of the problem is this incomplete. When you face a freeze of this kind, you need:
- make sure you understand the topology of the pipeline; you need to understand (and include in a question like this) details on participating filters and pin connections
- make sure you stop graph from proper thread, specifically not from certain filter callback
- attach a debugger and check thread states, however not just the thread which calls the freezing
Stop
(which is likely to have zero meaningful detail) but other threads as well, to find others relevant that prevent from stop synchronization.
The problem is typically your code causing a deadlock on stop of streaming, or a buggy participating filter.