Today I ran into an issue when using the .Net SqlDependency class when calling SqlDependency.Start(connectionName, queueName). The class would throw the exception "KeyNotFound" - "The given key was not present in the dictionary.". After scratching my head for a few moments I found that in the queue there were a number of messages stuck in the queue that did not have conversation handles that did not exist.
It is possible that somewhere in my code it did not call SqlDependency.Stop() when the webserver was recycled or due to an unhandled exception - but could easily have been Service Broker itself.
I found the solution was to clear the queue of any items that had invalid conversation handles (or completely clear the queue).
DECLARE item_cursor CURSOR LOCAL FAST_FORWARD FOR SELECT s.conversation_handle FROM clients.dbo.MySBQueueName s LEFT JOIN sys.conversation_endpoints e ON e.conversation_handle=s.conversation_handle WHERE e.conversation_handle IS NULL; -- or completely clear it below --SELECT s.conversation_handle FROM clients.dbo.MySBQueueName s; OPEN item_cursor DECLARE @conversation UNIQUEIDENTIFIER FETCH NEXT FROM item_cursor INTO @conversation WHILE @@FETCH_STATUS = 0 BEGIN END CONVERSATION @conversation WITH CLEANUP FETCH NEXT FROM item_cursor INTO @conversation END
There wasn't much on Google about this error (though people are reporting it), I hope this helps someone.
Michael Brown, 360 Replays Ltd. (don't forget that 'Mark As Answer' button!)