Reputation: 24067
I would like to rephrase my previous question How to create Singleton with async method?
Imagine messaging application (like icq) - something that should be always connected to server and can post messages.
I need to implment class Connection
. It should be singleton, because it contains "socket" inside and that socket should persist during entirely application lifetime.
Then I want to implement async method Connection.postMessage
Because postMessage
can take significant ammount of time:
postMessage
should be asyncpostMessage
should queue messages if neccesaryNote my application posts dozens messages per second, so it is not appropiate to create new Thread for each postMessage
call.
I diffenetely need to create exactly one extra thread for messages posting but I don't know where and how.
upd: good example http://msdn.microsoft.com/en-us/library/yy12yx1f(v=vs.80).aspx
Upvotes: 1
Views: 1090
Reputation: 13574
jp,
You're looking at a classic producer/consumer problem here... During initialisation the Connection
should create a MessageQueue
start a Sender
in it's own background thread.
Then the connection posts
just messages to the queue, for the Sender to pickup and forward when ready.
The tricky bit is managing the maximum queue size... If the producer consistently outruns the consumer then queue can grow to an unmanagable size. The simplest approach is to block the producer thread until the queue is no longer full. This can be done with a back-off-ARQ. ie: while(queue.isFull) sleep(100, "milliseconds"); queue.add(message);
If you don't require 100% transmission (like a chat-app, for instance) then you can simply throw a MessageQueueFullException, and the poor client will just have to get over it... just allways allow them to resubmit later... allowing the user manage the retrys for you.
That's how I'd tackle it anyway. I'll be interested to see what others suggestions are muted.
Hope things work out for you. Cheers. Keith.
Upvotes: 1
Reputation: 273179
No, Postmessage (itself) should not be async .
It should
And the Processing Thread should
What you have is a classic Producer/Consumer situation with 1 Consumer and multiple Producers.
PostMessage is the entry-point for all producers.
Upvotes: 3