It's so long since we've posted anything here...
Today we will speak a little about CCR... "Microsoft's light weight concurrency
library"
What is CCR?
It's the abbreviation for Concurrency and Coordination Runtime.. which is a library
that Microsoft recently released with Microsoft
Robotics Studio library..
CCR solves a lot of troubles we usually face when coding using Threads (and we will
see shortly how)..
Consider this sample (non-real) code:
void OnOkay(Okay state)
{
// Dothings
}
void OnCancel(Cancel state)
{
// Do Other things
}
and considering that you want to work asynchronously, that's you want to wait for a message (Okay or Cancel), know it's type and then call the aproperciate method for it, then wait for another message... etc, something like this:
void ReadMessages()
{
while (true)
{
Message message = PullMessage(DispatchQueue);
switch(typeof(message))
{
case Okay:
OnOkay(message as Okay);
...
}
}
Just that simple...
BUT, now your method waits till the handler finishes before polling the next message...
What to do ?
We can make a thread to run the handler in.. so, instead of doing this:
case Okay:
OnOkay(message as Okay);
we will replace it with
case Okay:
Thread thread = new Thread(new ThreadStart(delegate(){
OnOkay(message as Okay);
}));
thread.Start();
Again, just simple..
Now, what if I told you that the DispatcherQueue is accessed from so many threads,
What to do?
Okay, simple, put a lock statement to prevent multiple threads from accessing the
Queue at the same time..
Simple...
Now, What if it's just like this:
port.Post(new Okay());
and
port.Post(new Cancel());
and it's thread safe, controls the number of threads open, just that neat.
Isn't that better?
CCR doesn't offer a new technology, it's just an elegant way to manage you thread
pools and conccurent tasks.
A few definitions:
- Dispatcher Class:
It's basically a ThreadPool.. which we can consider like a List of threads.. but it has a predefined number of threads (that can be passed in the constructor)
Dispatcher Dispatcher = new Dispatcher(5);
- DispatcherQueue Class:
It's a queue of delegates each holds a handler that's waiting for certain type of messages. - Port:
Something that you send/receive through... it's a virtual port (think about it like your printer/scanner port) - Arbiter:
A static class that manges adding/removing your methods (wrapped in delegate objects)
Wait the next paper to give some sample code and explanation...
Till then, you can check a good resource: MSDN.. About CCR
Stay in touch...
Alsalam alikom wa ra7mat Allah wa barakatoh