I am new writing singleton classes but I am running into a weird behavior. On my singleton class I have an event that is only firing once. This event is the ReceiveCompleted of the System.Messaging.MessageQueue class. My singleton class has a method GetCartAsync that requests information from another application via MSMQ to the "FleetClientQueue" queue which is the queue that the ReceiveCompleted is subscribed to. Here is the singleton class:
public sealed class CartRepository : ICartRepository
{
private CartRepository()
{
if (!MessageQueue.Exists(string.Format(".\\Private$\\FleetClientQueue"))) ;
{
fleetClientQueue = MessageQueue.Create(".\\Private$\\FleetClientQueue");
fleetClientQueue.SetPermissions("Everyone", MessageQueueAccessRights.FullControl, AccessControlEntryType.Allow);
}
fleetClientQueue = new MessageQueue(".\\Private$\\FleetClientQueue");
fleetClientQueue.Formatter = new XmlMessageFormatter(new[] { typeof(Cart) });
fleetClientQueue.ReceiveCompleted += FleetClientQueue_ReceiveCompleted;
fleetClientQueue.BeginReceive();
}
static ManualResetEvent expectedEchoReceived = new ManualResetEvent(false);
Cart _cart = new Cart();
static MessageQueue fleetClientQueue;
private static CartRepository instance = null;
public static CartRepository Instance
{
get
{
if (instance == null)
{
instance = new CartRepository();
}
return instance;
}
}
private void FleetClientQueue_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
{
_cart = (Cart)e.Message.Body;
expectedEchoReceived.Set();
}
public async Task<Cart> GetCartAsync()
{
MessageQueue fleetClientServiceQueue;
fleetClientServiceQueue = new MessageQueue(".\\Private$\\FleetClientServiceQueue");
fleetClientServiceQueue.Formatter = new BinaryMessageFormatter();
fleetClientServiceQueue.Send("RequestCartInformation");
expectedEchoReceived.Reset();
expectedEchoReceived.WaitOne(5000);
return _cart;
}
}
Here is the code of how I am calling the method on the singleton class from a viewmodel class:
Cart = await CartRepository.Instance.GetCartAsync();
The weird part is that the first time GetCartAsync method is called the ReceiveCompleted event fires just fine. After that for some reason when I called the GetCartAsync from another view models in my application the ReceiveCompleted event is not fired. I can see the messages coming in into that queue on computer management and they just keep accumulating on the queue since it looks like they are not being processed by the singleton subscribed event.
Please if I can get some ideas of what is going on please.