Question

In My Parallel.Foreach Loop I am calling

              _helper.subscribeUserEndPoint(loop._contactGrpSvcs);

_helper is the Encapsulating class for the UserEndPoint and all other operations like Subscribes

The Subscribe methods are:

        public void subscribeUserEndPoint(ContactGroupServices cntGrpSvcs)
        {

            cntGrpSvcs.BeginSubscribe(TerminateSubscribe, cntGrpSvcs);

            _contactSubscribeCompleted.WaitOne();

            LOG.Info("Returning from Successful Subscribe Endpoint");
        }


    private void TerminateSubscribe(IAsyncResult result)
    {

        ContactGroupServices cntGrpSvcs = result.AsyncState as ContactGroupServices;
        try
        {
            cntGrpSvcs.EndSubscribe(result);
        }
        catch (Exception ex)
        {
            LOG.Error("Failed to Complete Subscribe. " + ex.StackTrace);
        }
        CollaborationSubscriptionState state = cntGrpSvcs.CurrentState;
        LOG.Info("Subscribed State = " + state.ToString());

            _contactSubscribeCompleted.Set();

    }

The Threads Deadlock while waiting on _contactSubscribeCompleted.WaitOne(); What's a way to avoid this deadlock contention ?

Cheers,

  -- Brian

PS: One Reason the deadlocks could be occuring is because of an inherent problem with the AutoResetEvent -- From the documentation -- "There is no guarantee that every call to the Set method will release a thread. If two calls are too close together, so that the second call occurs before a thread has been released, only one thread is released. It is as if the second call did not happen. Also, if Set is called when there are no threads waiting and the AutoResetEvent is already signaled, the call has no effect. " Is there a Workaround to this ??

Was it helpful?

Solution

By calling the begin method and then waiting for the operation to complete, you are calling the api in a completely synchronous manner. It's easier to do that without the waithandle. You can just chain the begin and end methods together.

public void subscribeUserEndPoint(ContactGroupServices cntGrpSvcs)
{
  try
  {
    cntGrpSvcs.EndSubscribe(cntGrpSvcs.BeginSubscribe(null, null));
    CollaborationSubscriptionState state = cntGrpSvcs.CurrentState;
    LOG.Info("Subscribed State = " + state.ToString());
    LOG.Info("Returning from Successful Subscribe Endpoint");
  }
  catch (Exception ex)
  {
    LOG.Error("Failed to Complete Subscribe. Exception: " + ex.ToString());
  }   
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top