public bool WaitForComplete()
{
try
{
WaitHandle waitHandle = null;
int timeout = Timeout.Infinite;
lock (m_lock)
{
if (m_exception != null)
{
throw new ServiceResultException(m_exception, StatusCodes.BadCommunicationError);
}
if (m_deadline != DateTime.MinValue)
{
timeout = (int)(m_deadline - DateTime.UtcNow).TotalMilliseconds;
if (timeout <= 0)
{
return false;
}
}
if (m_isCompleted)
{
return true;
}
if (m_waitHandle == null)
{
m_waitHandle = new ManualResetEvent(false);
}
waitHandle = m_waitHandle;
}
if (waitHandle != null)
{
try
{
#if !SILVERLIGHT
if (!m_waitHandle.WaitOne(timeout, false))
{
return false;
}
#else
if (!m_waitHandle.WaitOne(timeout))
{
return false;
}
#endif
lock (m_lock)
{
if (m_exception != null)
{
throw new ServiceResultException(m_exception, StatusCodes.BadCommunicationError);
}
}
}
catch (ObjectDisposedException)
{
return false;
}
}
}
finally
{
// always stop the timer after operation completes.
lock (m_lock)
{
if (m_timer != null)
{
try
{
m_timer.Dispose();
m_timer = null;
}
catch (Exception)
{
// ignore
}
}
}
// release the wait event.
if (m_waitHandle != null)
{
try
{
m_waitHandle.Close();
m_waitHandle = null;
}
catch (Exception)
{
// ignore
}
}
}
return true;
}