SlideShare ist ein Scribd-Unternehmen logo
1 von 46
Downloaden Sie, um offline zu lesen
CCR
No More Asynchronous Spaghetti


      An Introduction

          Presented by Igor Moochnick
Concurrency: is it necessary?
 Concurrent programming is how to make your
  application to scale by doing more things at once.
 If you have one CPU – you can do only one thing at a
  time, but it doesn't mean it is actually DOING
  something most of the time - in fact, 99% of the time,
  your CPU is literally turned off.
 Nowadays more and more machines have more than
  one core, these machines CAN do more than one
  thing at once.
 Don’t overdesign! Not every problem can or should
  be solved with a concurrent solution.
What is CCR?
 Concurrency and Coordination Runtime
 CCR is a lightweight distributed services-
  oriented architecture and a common
  language runtime (CLR)-based library.
 The CCR makes programming asynchronous
  behavior much simpler than the typical
  challenge of writing threaded code.
 CCR expresses concurrent programs in
  explicit continuation passing (CPS) style
  which is often quite an arduous way for a
  human to express concurrent calculations.
What is CCR?
 Has nothing to do with a runtime, though. It’s
  a managed library that can be used from any
  managed language: C#, VB.NET, etc...
 Released (December 12, 2006) as part of the
  Microsoft Robotics Studio, but can be used as
  a standalone library (check the license!)

 Here is a short explanation …
A lot of asynchronous events?




   Tired of asynchronous code coordination?
      Do you see a resemblance?
Glimpse into your future




           He definitely used the CCR !
Example (compare APM & CCR)
 Need to schedule 2 (or more) asynchronous
  operations and, as soon as all of them complete,
  execute some action

 How to start with CCR?
    Add a reference to the Ccr.Core.dll
    using Microsoft.Ccr.Core;
    Create Dispatcher
    Create DispatcherQueue
    Create ports
    Declare actions (handlers)
Dispatcher class
 Configurable number of threads – on construction.
  Default: 1 thread for every CPU (if 1 CPU – 2 threads).
 No dynamically creating or destroying threads.
 Possible to set threads' scheduling priority.
  Default: normal priority.
 Unlike CLR:
    No dynamical thread to change number of thread pool
     threads based on the workload – streamlined, simple
     and high-performance code.
    No limitation on number of thread pools (dispatcher
     instances) with different thread priorities for different
     kind of tasks.
 For debugging – gives a name for each thread.
Dispatcher Queue
 Maintains a queue of delegates that identify
  methods ready to execute.
 Dispatcher's threads wait for entries to
  appear in the DispatcherQueue.
 Order is not important (whatever comes first:
  events or entries).
 Use as many queues as you need.
 Unlike CLR: Dispatcher dequeue equally
  (round-robin) from all the associated queues.
  Useful for different priority tasks.
 Default constructor – CLR thread pool
Ports and PortSets
 First-In-First-Out (FIFO)
 Possible to instantiate a port with up to 16 different
  types. Port (that carries multiple values) works by
  maintaining unrelated sub-ports for each type.
      PortSet<int,string> pIS = new PortSet<int,string>();
       Reading an int value from pIS = reading from the sub-
       port that contains ints. This read operation is
       unaffected by the state of the string sub-port.
 Test() to atomically remove a value from a port (if the
  port is not empty).
 If no ReceiverTask objects are registered or if none
  of the registered ReceiverTask objects want the item,
  the item is added to the Port's internal queue.
CCR Architecture
 Items are posted into a Port object.
 Registered ReceiverTasks send the items to their arbiters,
  which decide what callback method should ultimately execute to
  process the posted item.
 The Arbiter then queues the work item task into a
  DispatcherQueue, and a Dispatcher (or CLR thread pool) thread
  will execute the method processing the posted item.
Arbiter
 Arbiter is a static class that defines factories
  that create other Arbiters
 In fact each constructed Arbiter contains a
  reference to one or more constructed
  ReceiverTask objects
 You must activate the arbiters by calling
  Arbiter's Activate method. This will register all
  of the arbiter's ReceiverTask objects with the
  Ports and it tells the arbiter which
  DispatcherQueue to post work item tasks to
  as Port items are processed.
Single Item Receiver                    Handler




 Port<int> p = new Port<int>();
  Arbiter.Activate (dispatcherQueue,
  Arbiter.Receive(false, p, delegate (int i)
  {
      // … do something …
      Console.WriteLine(i) ;
  }) );
  p.Post(10);

 Output:
  10
Persisted Arbiters
 Some Arbiters can be persisted or not
 Choice and Interleave's
  TeardownReceiverGroup require that their
  arbiters always be non-persistent

 If you forget to activate your arbiters, items
  will continue to queue up in Port objects but
  they will NEVER get processed!
Multiple Item Receiver                                                 Handler




 Will be called only when the configured number of
  items has accumulated on the associated port or one
  item across multiple ports.
 An array of items will be passed atomically to the
  handler.
   Arbiter.MultipleItemReceive<T0>(bool persist, Port<T0> port, int messageCount,
    VariableArgumentHandler<T0> handler);

   Arbiter.MultipleItemReceive<T0,T1>(PortSet<T0,T1> port,
    Handler<ICollection<T0>, ICollection<T1>> handler);

   Arbiter.MultiplePortReceive<T0>(bool persist, Port<T0> [] ports,
    VariableArgumentHandler<T0> handler);
Example: Hello World! in Math
(Matrix Multiplication)




 From site: Scalar and Matrix Multiplication
Data Flow Diagram
     portMatrix1       portMatrix2                 portSum            portResult




                                                             Result




                                               +
       Multiply    *                  Sum
       handler                       handler




 Simplified graphical representation of the data
  flow in the Matrix multiplication example
Example: racing conditions
 STOP! There is a catch!
 Change the number of threads for the Dispatcher to 0
  (it’ll use a default number of worker threads)
 Result is changing all the time


 Dispatcher is providing a real scheduling of work
  items across multiple CPUs and Threads

 Order is unpredictable !!!
  Never count on it !!!
Common Arbiters
 single item receivers for specifying handlers
  on a single port
 a choice arbiter which will chose which of two
  receivers to fire based on the availability of
  messages
 an interleave arbiter (explained later)
 a join arbiter for static join expressions
 MultipleItemReceive arbiters for specifying
  dynamic joins
Predefined Arbiters (partial list)
 FromHandler            Just executes a method (not associated
                            with a port)
 FromIteratorHandler      Execute until enumerator is done (not
                            associated with a port)
 Receive                  Process a single item from a port
 MultipleItemReceive      Process a bunch of items at once
 MultiplePortReceive      Process a single item from multiple ports
                            (one item per port)
 JoinedReceive            Process multiple items from 2 ports (one
                            item per port)
 Choice                   Executes one & only one method from a
                            set of methods
 Interleave               Calls back a set of methods to process
                            items from various ports. Arbiter is similar
                            to a reader/writer thread synchronization
                            lock
Choice Arbiter                                                  Handler



    Arbiter.Choice(PortSet<T0, T1> resultPort, Handler<T0> h0, Handler<T1> h1);
    Arbiter.Choice(params ReceiverTask[] receivers);

 The choice arbiter allows one to specify that one of two (or
   more) branches should fire and the others should be discarded.
   For example using the first method:
 Example:
   Arbiter.Activate(taskQueue,
      Arbiter.Choice(
          Arbiter.Receive(false, port1, MyIntHandler),
          Arbiter.Receive(false, port2, MyStringHandler)
      )
   );

   Will run either MyIntHandler or MyStringHandler but not both.
   The choice will be determined by the availability of int or string
   message on the ports and if both types of messages are
   available then a non-deterministic choice is made.
Join Arbiter                                                           Handler



   Arbiter.Activate(dispatcherQueue,
    Arbiter.JoinedReceive<int,string>(true, p1,p2, IntAndStringJoinedHandler) );

 The above will schedule the execution of the
    IntAndStringJoinedHandler when values can be
    atomically read on ports p1 AND p2 and will
    continue doing so as long as messages are available
    (in this example its a persisted receiver). The handler
    will be passed the values that were read. One can
    join over several ports of different types.
 MultiportReceive is a form of a Join Arbiter:
    Arbiter.MultiplePortReceive<T0>(bool persist, Port<T0> [] ports,
    VariableArgumentHandler<T0> handler);
Handler

Interleave Arbiter
                                                    Handler
                                                     Handler




   Arbiter.Interleave(
       TeardownReceiverGroup teardownGroup,
       ExclusiveReceiverGroup exclusiveGroup,
       ConcurrentReceiverGroup concurrentGroup
    );

 Expresses concurrent calculations
 Corresponds to multiple reads but single writers to a shared
  state. Its a more high level, far more concise way to capture
  advanced protection schemes.
 The one time (non-persistent) shutdown handler (any one from
  the TeardownReceiverGroup) will cause the entire interleave to
  stop, guaranteeing no delegates are running or will ever run
  again. Makes clean up easy!
 Why not to use join?
    Interleave is error prone for this kind of operations.
Interleave Arbiter: continues
 Teardown will occur when all handlers have
  stopped executing (it has strong guarantees).
  It will not wait until all queued messages have
  executed, only just when all handlers
  currently running are done. At least that is the intent.
 The interleave arbiter is biased towards
  exclusive handlers and the teardown group,
  so any more queued messages will not be
  processed the moment an exclusive or
  teardown message is received.
Iterators: no more CPS
   Arbiter.Activate(dq, Arbiter.FromIteratorHandler(SaveWebSiteToFile));
    IEnumerator<ITask> SaveWebSiteToFile() { … }

   Arbiter.Activate(dq,Arbiter.ReceiveWithIterator(false,port,DoWorkHandler));
    IEnumerator<ITask> DoWorkHandler(DoWork w) { … }

 Inheriting from the IEnumerator interface allows one
  to specify "yield" points in a method at which control
  flow returns to the caller. When a MoveNext() method
  is called on such a method control flow resumes from
  the “yield” point, not from the start of the method.
 The coordination primitives in CCR all inherit from the
  ITask interface and this is used to help identify the
  iteration variable for use with the IEnumerator
  interface.
Iterator: example
public void Start()
{
  Arbiter.Activate(taskQueue, Arbiter.ReceiveWithIterator(false, pMain, DoWorkHandler));
}

IEnumerator<ITask> DoWorkHandler(DoWork w)
{
  DoWork workA = new DoWork();
  Result r = null;

    // send message to ServiceA
    pServiceA.Post(workA);

    // yield for result on response port attached to outbound message
    yield return Arbiter.Choice(workA.pResponse,
        delegate (Result Res) { r = Res;},
        delegate (Failure F) { Trace.WriteLine("Failed");} );

    // when either branch above happens, we will continue executing
    // here without ever having blocked a thread!
    if (r == null) yield break; // error occurred, break iteration

    // send next message, depending on the result from A
    DoWork workB = new DoWork(r);
    pServiceB.Post(workB);
    // ... handle result form B etc.
}
More on iterators
 Schedule a task that will iterate over some
  message coordination

  dispatcherQueue.Enqueue(new IterativeTask<int>(message, MyIntIterator));
  IEnumerator<ITask> MyIntIterator(int message)
  {
     Console.WriteLine(“got: {0}”, message); yield break;
  }


 You can also associate a Reissue receiver
  with a port and an iterator Handler
  Arbiter.Activate(dispatcherQueue,
         Arbiter.ReceiveWithIterator(true, port, DoWorkHandler));
Enumerator Handler limitations
 static IEnumerator<ITask> Handler()
   {
      yield return Arbiter.FromHandler(delegate()
                              { Console.WriteLine("I got here..."); });
      yield break;
   } BAD!

 You can’t yield to any handler. You must yield to a receive, a
   choice or a join (or multiple item receive).

 This is a limitation of the current version of the CCR. To get
   around this you can of course create a simple port, post and
   then yield return:
   Port<bool> port = new Port<bool>();
   port.Post(true);
   yield return Arbiter.Receive(false,port,delegate(bool b){ … });
Don’t starve
 Very hard to locate a blocked or misbehaving thread
  in the pool (very easy in GUI – only one thread)
 System.Threading.Timer is a convenient way to shoot
  yourself in the foot – all instances are using the same
  thread pool (size: 50)
 Few simple guidelines to avoid starvation:
      Avoid using blocking I/O in an event handler.
      Split individual, long-running computations into several
       shorter ones.
      Choose useful intervals for timer-driven behavior.
      Serialize timer events of the same activity.
Timeouts – don’t hang forever
 Never forget about Timeouts

 Tell the DispatcherQueue to wait and then to post the
  current date and time into the timeoutPort:

  Port<DateTime> timeoutPort = new Port<DateTime>();
  dq.EnqueueTimer(TimeSpan.FromMinutes(2), timeoutPort);
  Arbiter.Receive(false, timeoutPort,
  delegate(DateTime dt)
  {
     // … do stuff …
  });
Predicates = filters
 A sample equal thousand words:

   Port<int> Port = new Port<int>();

    Arbiter.Activate(taskQueue,
    Arbiter.Receive(true, Port, HandlerThatRunsOnlyWithLargeInts, MyLargeIntegerFilter),
    Arbiter.Receive(true, Port, HandlerThatRunsOnlyWithSmallInts, MySmallIntegerFilter),
    Arbiter.Receive(true, Port, MyCatchAllIntHandler));

    bool MyLargeIntegerFilter(int i)
    {
      if (i> 1000000) return true;
      else            return false;
    }
Web Crawler – problem definition
 Create a smart web crawler that will
  download images and the pages themselves
  recursively from the web.
 Flush the downloaded content to your hard
  drive.
 Download requests should timeout if hanged.
 Code should be 100% asynchronous.
Web Crawler – non-goals
 Limit the depth of the recursion with a
  configurable parameter.
 Download only pages descendants of the root
  site.
 Save each page (and all its images) into it’s
  own folder.
 Preserve the relationship of the pages, while
  writing to the disk, as nested folders.
 Show the progress on the Windows form
  without affecting the user’s experience (non-
  blocking display).
Web Crawler – the strategy
 Provide a continuous stream of URLs
     Interleave?
     FromIteratorHandler?
     Better: persistent Receive handler
 Each URL request will either succeed, fail or
  timeout
     Definitely the Choice arbiter with timeout port
 As soon as download completed – schedule
  the asynchronous write
     Choice arbiter – success or failure
Web Crawler – code & demo

             YES !!!
          Unbelievable !!!




        IT WORKS!!!
        IT’S EASY!!!
What about WinForms?
 Use Microsoft.Ccr.Adapters.WinForms

   ManualResetEvent MainThreadEvent = new ManualResetEvent(false);
    // Bind dispatcher queue to WinformsAdaptor
    WinFormsServicePort port = WinFormsAdapter.Create(dispatcherQueue);
    port.Post(new RunForm(delegate
    {
       form = new WebCrawlerForm(port);
       form.HandleDestroyed += delegate(object sender, EventArgs e)
                                 { MainThreadEvent.Set(); };
       return form;
     }));
    // Wait for a “shutdown” signal
    MainThreadEvent.WaitOne();
    // We need to inform the WinFormsAdaptor that it is about to quit.
    port.Post(new Shutdown());
    // Let the system to finalize everything
    System.Threading.Thread.Sleep(500);
Causality ~ <try/catch>
 Causalities are a generalization of try/catch, across
  threads and processors, of the nested exception
  handling mechanism. Much more powerful however
  since it can deal with Joins (two different causalities
  coming together in a common handler).
 They are NOT transactions
 When an exception is thrown, within any logically
  related descendant of a Post operation, that
  exception can be cleanly caught and dealt within one
  place.
 The CoordinationPort allows anyone within a
  causality to post a message to the "owner" of the
  causality, allowing you to implement all kinds of
  internal communication protocols.
Causality: example
 Port<Exception> pException = new Port<Exception>();

   Arbiter.Activate(dispatcherQueue, Arbiter.Receive(false, pException,
   /* ExceptionHandler */ delegate(Exception ex)
   {
        System.Diagnostics.Trace.WriteLine(ex.ToString());
   }));
   Arbiter.Activate(dispatcherQueue, Arbiter.FromHandler(delegate
   {
   // Define Causality scope (owner)
      Dispatcher.AddCausality(new Causality("test", pEx));
   // … do some stuff … that spawn AsynchronousHandler …
   }
  void AsynchronousHandler()
 {
  // … do some more stuff that throws exception
     throw new Exception(“bad things happen …”);
  }
Advanced CCR: the next steps
 The observer pattern (what is called pub/sub or
  publication/subscription) can be implemented using
  the Subscription service. The service (implemented
  using the CCR) keeps a list of ports, and then posts
  the message N items (one for each subscriber).
  Service’s can be observed, used across
  nodes/machines. This keeps the CCR simple.
 See Service Tutorials 4,5,6 for more info.

 If a service is overkill in your scenario, you can write
  a simple class that does this: keeps a list of ports and
  replicates messages on them. Or you can write a
  simple arbiter (derive from Receiver) that does this.

 Service orchestration …
Meet BOB (version 1)
 Robot (self programmable), controlled by the
  CCR (running on Mobile device - PDA)
 Communicates with a main computer to
  upload gathered information and to get new
  instructions
MS Robotics Studio (MSRS)




 Writing an application using Microsoft Robotics Studio is a simple
   matter of orchestrating input and output between a set of services.
   Services represent the interface to software or hardware and
   allow you to communicate between processes that perform
   specific functions.
Simulation Runtime




 Simulation runtime can be used in a variety of advanced
  scenarios with high demands for fidelity, visualization and scaling.
  At the same time a novice user can use simulation with little to no
  coding experience and develop interesting applications.
VPL – Visual Programming Language




 Application development environment designed on a
  graphical dataflow-based programming model
Conclusion
 The CCR is a CLR library that provides a consistent
  and scalable way to program asynchronous
  operations and coordinate among multiple responses.
 Framework Class Library (FCL) classes, that already
  support the CLR's asynchronous programming model
  (such as Stream's BeginRead and BeginWrite
  methods) can be easily wrapped, allowing existing
  types to integrate with the CCR so that complex
  failure handling and coordination patterns can be
  coded in a robust, reliable and concise way.
 The use of C# iterators for scheduling operations
  allows sequential programming without blocking OS
  threads, thus enabling scaling without sacrificing the
  simplicity of sequential code.
Acronyms
 CCR – Concurrency and Coordination
  Runtime
 APM – Asynchronous Programming Model
 CPS – Continuous Passing Style
 CLR – Common Language Runtime
 FCL – Framework Class Library
 MSRS – Microsoft Robotics Studio
Links
 CCR Wiki
 http://channel9.msdn.com/wiki/default.aspx/Channel9.ConcurrencyRuntime

 CCR Patterns
 http://channel9.msdn.com/wiki/default.aspx/Channel9.CcrPatterns

 MSRS Home
 http://msdn.microsoft.com/robotics/


 My e-mail: igormoochnick@yahoo.com
 My new Blog:             http://igorshare.blogspot.com/
 My new Web Site:
 http://igor.moochnick.googlepages.com/

Weitere ähnliche Inhalte

Was ist angesagt?

What is storage class
What is storage classWhat is storage class
What is storage classIsha Aggarwal
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in PracticeAlina Dolgikh
 
Using QString effectively
Using QString effectivelyUsing QString effectively
Using QString effectivelyRoman Okolovich
 
The Kumofs Project and MessagePack-RPC
The Kumofs Project and MessagePack-RPCThe Kumofs Project and MessagePack-RPC
The Kumofs Project and MessagePack-RPCSadayuki Furuhashi
 
Towards an Integration of the Actor Model in an FRP Language for Small-Scale ...
Towards an Integration of the Actor Model in an FRP Language for Small-Scale ...Towards an Integration of the Actor Model in an FRP Language for Small-Scale ...
Towards an Integration of the Actor Model in an FRP Language for Small-Scale ...Takuo Watanabe
 
Variables: names, bindings, type, scope
Variables: names, bindings, type, scopeVariables: names, bindings, type, scope
Variables: names, bindings, type, scopesuthi
 
Behavioral Reflection
Behavioral ReflectionBehavioral Reflection
Behavioral ReflectionMarcus Denker
 
Ti1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and ScopesTi1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and ScopesEelco Visser
 
FreeRTOS Xilinx Vivado: Hello World!
FreeRTOS Xilinx Vivado: Hello World!FreeRTOS Xilinx Vivado: Hello World!
FreeRTOS Xilinx Vivado: Hello World!Vincent Claes
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in JavaAllan Huang
 
Regular types in C++
Regular types in C++Regular types in C++
Regular types in C++Ilio Catallo
 
Exploitation of counter overflows in the Linux kernel
Exploitation of counter overflows in the Linux kernelExploitation of counter overflows in the Linux kernel
Exploitation of counter overflows in the Linux kernelVitaly Nikolenko
 
Thrfit从入门到精通
Thrfit从入门到精通Thrfit从入门到精通
Thrfit从入门到精通炜龙 何
 
Tokyo Cabinet & Tokyo Tyrant
Tokyo Cabinet & Tokyo TyrantTokyo Cabinet & Tokyo Tyrant
Tokyo Cabinet & Tokyo Tyrant輝 子安
 

Was ist angesagt? (20)

C++11 talk
C++11 talkC++11 talk
C++11 talk
 
Pthread
PthreadPthread
Pthread
 
What is storage class
What is storage classWhat is storage class
What is storage class
 
Lockless
LocklessLockless
Lockless
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
Linux Internals - Part III
Linux Internals - Part IIILinux Internals - Part III
Linux Internals - Part III
 
Using QString effectively
Using QString effectivelyUsing QString effectively
Using QString effectively
 
The Kumofs Project and MessagePack-RPC
The Kumofs Project and MessagePack-RPCThe Kumofs Project and MessagePack-RPC
The Kumofs Project and MessagePack-RPC
 
Towards an Integration of the Actor Model in an FRP Language for Small-Scale ...
Towards an Integration of the Actor Model in an FRP Language for Small-Scale ...Towards an Integration of the Actor Model in an FRP Language for Small-Scale ...
Towards an Integration of the Actor Model in an FRP Language for Small-Scale ...
 
Variables: names, bindings, type, scope
Variables: names, bindings, type, scopeVariables: names, bindings, type, scope
Variables: names, bindings, type, scope
 
Behavioral Reflection
Behavioral ReflectionBehavioral Reflection
Behavioral Reflection
 
Jvm memory model
Jvm memory modelJvm memory model
Jvm memory model
 
Ti1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and ScopesTi1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and Scopes
 
FreeRTOS Xilinx Vivado: Hello World!
FreeRTOS Xilinx Vivado: Hello World!FreeRTOS Xilinx Vivado: Hello World!
FreeRTOS Xilinx Vivado: Hello World!
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in Java
 
Regular types in C++
Regular types in C++Regular types in C++
Regular types in C++
 
P threads
P threadsP threads
P threads
 
Exploitation of counter overflows in the Linux kernel
Exploitation of counter overflows in the Linux kernelExploitation of counter overflows in the Linux kernel
Exploitation of counter overflows in the Linux kernel
 
Thrfit从入门到精通
Thrfit从入门到精通Thrfit从入门到精通
Thrfit从入门到精通
 
Tokyo Cabinet & Tokyo Tyrant
Tokyo Cabinet & Tokyo TyrantTokyo Cabinet & Tokyo Tyrant
Tokyo Cabinet & Tokyo Tyrant
 

Ähnlich wie CCR No More Asynchronous Spaghetti

Introduction to Thrift
Introduction to ThriftIntroduction to Thrift
Introduction to ThriftDvir Volk
 
Porting a Streaming Pipeline from Scala to Rust
Porting a Streaming Pipeline from Scala to RustPorting a Streaming Pipeline from Scala to Rust
Porting a Streaming Pipeline from Scala to RustEvan Chan
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading PresentationNeeraj Kaushik
 
Os Reindersfinal
Os ReindersfinalOs Reindersfinal
Os Reindersfinaloscon2007
 
Os Reindersfinal
Os ReindersfinalOs Reindersfinal
Os Reindersfinaloscon2007
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/MultitaskingSasha Kravchuk
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streamsjessitron
 
Qt everywhere a c++ abstraction platform
Qt everywhere   a c++ abstraction platformQt everywhere   a c++ abstraction platform
Qt everywhere a c++ abstraction platformDeveler S.r.l.
 
Scaling Apache Storm - Strata + Hadoop World 2014
Scaling Apache Storm - Strata + Hadoop World 2014Scaling Apache Storm - Strata + Hadoop World 2014
Scaling Apache Storm - Strata + Hadoop World 2014P. Taylor Goetz
 
Cassandra 2.1 boot camp, Overview
Cassandra 2.1 boot camp, OverviewCassandra 2.1 boot camp, Overview
Cassandra 2.1 boot camp, OverviewJoshua McKenzie
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the wayOleg Podsechin
 
Operating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programmingOperating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programmingguesta40f80
 
002 hbase clientapi
002 hbase clientapi002 hbase clientapi
002 hbase clientapiScott Miao
 
Classic synchronization
Classic synchronizationClassic synchronization
Classic synchronizationhina firdaus
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard LibrarySantosh Rajan
 

Ähnlich wie CCR No More Asynchronous Spaghetti (20)

Introduction to Thrift
Introduction to ThriftIntroduction to Thrift
Introduction to Thrift
 
Porting a Streaming Pipeline from Scala to Rust
Porting a Streaming Pipeline from Scala to RustPorting a Streaming Pipeline from Scala to Rust
Porting a Streaming Pipeline from Scala to Rust
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading Presentation
 
Os Reindersfinal
Os ReindersfinalOs Reindersfinal
Os Reindersfinal
 
Os Reindersfinal
Os ReindersfinalOs Reindersfinal
Os Reindersfinal
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
Qt everywhere a c++ abstraction platform
Qt everywhere   a c++ abstraction platformQt everywhere   a c++ abstraction platform
Qt everywhere a c++ abstraction platform
 
(18.03.2009) Cumuy Invita - Iniciando el año conociendo nuevas tecnologías - ...
(18.03.2009) Cumuy Invita - Iniciando el año conociendo nuevas tecnologías - ...(18.03.2009) Cumuy Invita - Iniciando el año conociendo nuevas tecnologías - ...
(18.03.2009) Cumuy Invita - Iniciando el año conociendo nuevas tecnologías - ...
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
 
Scaling Apache Storm - Strata + Hadoop World 2014
Scaling Apache Storm - Strata + Hadoop World 2014Scaling Apache Storm - Strata + Hadoop World 2014
Scaling Apache Storm - Strata + Hadoop World 2014
 
Cassandra 2.1 boot camp, Overview
Cassandra 2.1 boot camp, OverviewCassandra 2.1 boot camp, Overview
Cassandra 2.1 boot camp, Overview
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the way
 
Apache Thrift
Apache ThriftApache Thrift
Apache Thrift
 
Operating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programmingOperating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programming
 
Go on!
Go on!Go on!
Go on!
 
002 hbase clientapi
002 hbase clientapi002 hbase clientapi
002 hbase clientapi
 
Classic synchronization
Classic synchronizationClassic synchronization
Classic synchronization
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
 
Storm
StormStorm
Storm
 

Mehr von Igor Moochnick

Continuous delivery workflow with Docker
Continuous delivery workflow with DockerContinuous delivery workflow with Docker
Continuous delivery workflow with DockerIgor Moochnick
 
Being a generalist and being great at what you do
Being a generalist and being great at what you doBeing a generalist and being great at what you do
Being a generalist and being great at what you doIgor Moochnick
 
The journey to container adoption in enterprise
The journey to container adoption in enterpriseThe journey to container adoption in enterprise
The journey to container adoption in enterpriseIgor Moochnick
 
Dev ops overview (brief)
Dev ops overview (brief)Dev ops overview (brief)
Dev ops overview (brief)Igor Moochnick
 
Dev ops cd tool chains
Dev ops cd tool chainsDev ops cd tool chains
Dev ops cd tool chainsIgor Moochnick
 
Tips for building responsive cloud applications
Tips for building responsive cloud applicationsTips for building responsive cloud applications
Tips for building responsive cloud applicationsIgor Moochnick
 
Building complex single page application should be as enjoyable as visit to a...
Building complex single page application should be as enjoyable as visit to a...Building complex single page application should be as enjoyable as visit to a...
Building complex single page application should be as enjoyable as visit to a...Igor Moochnick
 
Amazon 101 - building composite responsive apps - small
Amazon 101 - building composite responsive apps - smallAmazon 101 - building composite responsive apps - small
Amazon 101 - building composite responsive apps - smallIgor Moochnick
 
NO SQL: What, Why, How
NO SQL: What, Why, HowNO SQL: What, Why, How
NO SQL: What, Why, HowIgor Moochnick
 
Azure ServiceBus Queues and Topics
Azure ServiceBus Queues and TopicsAzure ServiceBus Queues and Topics
Azure ServiceBus Queues and TopicsIgor Moochnick
 
Arch factory - Agile Design: Best Practices
Arch factory - Agile Design: Best PracticesArch factory - Agile Design: Best Practices
Arch factory - Agile Design: Best PracticesIgor Moochnick
 
Best practices for agile design
Best practices for agile designBest practices for agile design
Best practices for agile designIgor Moochnick
 
Caliburn.micro jump start composite applications for WPF, Silverlight and WP7
Caliburn.micro jump start composite applications for WPF, Silverlight and WP7Caliburn.micro jump start composite applications for WPF, Silverlight and WP7
Caliburn.micro jump start composite applications for WPF, Silverlight and WP7Igor Moochnick
 
Building lean products with distributed agile teams
Building lean products with distributed agile teamsBuilding lean products with distributed agile teams
Building lean products with distributed agile teamsIgor Moochnick
 
Building Gwt Clients For Cloud Apps.Pptx
Building Gwt Clients For Cloud Apps.PptxBuilding Gwt Clients For Cloud Apps.Pptx
Building Gwt Clients For Cloud Apps.PptxIgor Moochnick
 

Mehr von Igor Moochnick (20)

Continuous delivery workflow with Docker
Continuous delivery workflow with DockerContinuous delivery workflow with Docker
Continuous delivery workflow with Docker
 
Being a generalist and being great at what you do
Being a generalist and being great at what you doBeing a generalist and being great at what you do
Being a generalist and being great at what you do
 
The journey to container adoption in enterprise
The journey to container adoption in enterpriseThe journey to container adoption in enterprise
The journey to container adoption in enterprise
 
Dev ops overview (brief)
Dev ops overview (brief)Dev ops overview (brief)
Dev ops overview (brief)
 
Dev ops cd tool chains
Dev ops cd tool chainsDev ops cd tool chains
Dev ops cd tool chains
 
Orchestration musings
Orchestration musingsOrchestration musings
Orchestration musings
 
Delivery pipelines
Delivery pipelinesDelivery pipelines
Delivery pipelines
 
Tips for building responsive cloud applications
Tips for building responsive cloud applicationsTips for building responsive cloud applications
Tips for building responsive cloud applications
 
Building complex single page application should be as enjoyable as visit to a...
Building complex single page application should be as enjoyable as visit to a...Building complex single page application should be as enjoyable as visit to a...
Building complex single page application should be as enjoyable as visit to a...
 
Amazon 101 - building composite responsive apps - small
Amazon 101 - building composite responsive apps - smallAmazon 101 - building composite responsive apps - small
Amazon 101 - building composite responsive apps - small
 
RavenDB overview
RavenDB overviewRavenDB overview
RavenDB overview
 
NO SQL: What, Why, How
NO SQL: What, Why, HowNO SQL: What, Why, How
NO SQL: What, Why, How
 
Azure ServiceBus Queues and Topics
Azure ServiceBus Queues and TopicsAzure ServiceBus Queues and Topics
Azure ServiceBus Queues and Topics
 
Arch factory - Agile Design: Best Practices
Arch factory - Agile Design: Best PracticesArch factory - Agile Design: Best Practices
Arch factory - Agile Design: Best Practices
 
Best practices for agile design
Best practices for agile designBest practices for agile design
Best practices for agile design
 
Caliburn.micro jump start composite applications for WPF, Silverlight and WP7
Caliburn.micro jump start composite applications for WPF, Silverlight and WP7Caliburn.micro jump start composite applications for WPF, Silverlight and WP7
Caliburn.micro jump start composite applications for WPF, Silverlight and WP7
 
Building lean products with distributed agile teams
Building lean products with distributed agile teamsBuilding lean products with distributed agile teams
Building lean products with distributed agile teams
 
Practical alm testing
Practical alm   testingPractical alm   testing
Practical alm testing
 
Putting SOAP to REST
Putting SOAP to RESTPutting SOAP to REST
Putting SOAP to REST
 
Building Gwt Clients For Cloud Apps.Pptx
Building Gwt Clients For Cloud Apps.PptxBuilding Gwt Clients For Cloud Apps.Pptx
Building Gwt Clients For Cloud Apps.Pptx
 

Kürzlich hochgeladen

The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFMichael Gough
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Karmanjay Verma
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 

Kürzlich hochgeladen (20)

The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDF
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 

CCR No More Asynchronous Spaghetti

  • 1. CCR No More Asynchronous Spaghetti An Introduction Presented by Igor Moochnick
  • 2. Concurrency: is it necessary?  Concurrent programming is how to make your application to scale by doing more things at once.  If you have one CPU – you can do only one thing at a time, but it doesn't mean it is actually DOING something most of the time - in fact, 99% of the time, your CPU is literally turned off.  Nowadays more and more machines have more than one core, these machines CAN do more than one thing at once.  Don’t overdesign! Not every problem can or should be solved with a concurrent solution.
  • 3. What is CCR?  Concurrency and Coordination Runtime  CCR is a lightweight distributed services- oriented architecture and a common language runtime (CLR)-based library.  The CCR makes programming asynchronous behavior much simpler than the typical challenge of writing threaded code.  CCR expresses concurrent programs in explicit continuation passing (CPS) style which is often quite an arduous way for a human to express concurrent calculations.
  • 4. What is CCR?  Has nothing to do with a runtime, though. It’s a managed library that can be used from any managed language: C#, VB.NET, etc...  Released (December 12, 2006) as part of the Microsoft Robotics Studio, but can be used as a standalone library (check the license!)  Here is a short explanation …
  • 5. A lot of asynchronous events? Tired of asynchronous code coordination? Do you see a resemblance?
  • 6. Glimpse into your future He definitely used the CCR !
  • 7. Example (compare APM & CCR)  Need to schedule 2 (or more) asynchronous operations and, as soon as all of them complete, execute some action  How to start with CCR?  Add a reference to the Ccr.Core.dll  using Microsoft.Ccr.Core;  Create Dispatcher  Create DispatcherQueue  Create ports  Declare actions (handlers)
  • 8. Dispatcher class  Configurable number of threads – on construction. Default: 1 thread for every CPU (if 1 CPU – 2 threads).  No dynamically creating or destroying threads.  Possible to set threads' scheduling priority. Default: normal priority.  Unlike CLR:  No dynamical thread to change number of thread pool threads based on the workload – streamlined, simple and high-performance code.  No limitation on number of thread pools (dispatcher instances) with different thread priorities for different kind of tasks.  For debugging – gives a name for each thread.
  • 9. Dispatcher Queue  Maintains a queue of delegates that identify methods ready to execute.  Dispatcher's threads wait for entries to appear in the DispatcherQueue.  Order is not important (whatever comes first: events or entries).  Use as many queues as you need.  Unlike CLR: Dispatcher dequeue equally (round-robin) from all the associated queues. Useful for different priority tasks.  Default constructor – CLR thread pool
  • 10. Ports and PortSets  First-In-First-Out (FIFO)  Possible to instantiate a port with up to 16 different types. Port (that carries multiple values) works by maintaining unrelated sub-ports for each type.  PortSet<int,string> pIS = new PortSet<int,string>(); Reading an int value from pIS = reading from the sub- port that contains ints. This read operation is unaffected by the state of the string sub-port.  Test() to atomically remove a value from a port (if the port is not empty).  If no ReceiverTask objects are registered or if none of the registered ReceiverTask objects want the item, the item is added to the Port's internal queue.
  • 11. CCR Architecture  Items are posted into a Port object.  Registered ReceiverTasks send the items to their arbiters, which decide what callback method should ultimately execute to process the posted item.  The Arbiter then queues the work item task into a DispatcherQueue, and a Dispatcher (or CLR thread pool) thread will execute the method processing the posted item.
  • 12. Arbiter  Arbiter is a static class that defines factories that create other Arbiters  In fact each constructed Arbiter contains a reference to one or more constructed ReceiverTask objects  You must activate the arbiters by calling Arbiter's Activate method. This will register all of the arbiter's ReceiverTask objects with the Ports and it tells the arbiter which DispatcherQueue to post work item tasks to as Port items are processed.
  • 13. Single Item Receiver Handler  Port<int> p = new Port<int>(); Arbiter.Activate (dispatcherQueue, Arbiter.Receive(false, p, delegate (int i) { // … do something … Console.WriteLine(i) ; }) ); p.Post(10);  Output: 10
  • 14. Persisted Arbiters  Some Arbiters can be persisted or not  Choice and Interleave's TeardownReceiverGroup require that their arbiters always be non-persistent  If you forget to activate your arbiters, items will continue to queue up in Port objects but they will NEVER get processed!
  • 15. Multiple Item Receiver Handler  Will be called only when the configured number of items has accumulated on the associated port or one item across multiple ports.  An array of items will be passed atomically to the handler.  Arbiter.MultipleItemReceive<T0>(bool persist, Port<T0> port, int messageCount, VariableArgumentHandler<T0> handler);  Arbiter.MultipleItemReceive<T0,T1>(PortSet<T0,T1> port, Handler<ICollection<T0>, ICollection<T1>> handler);  Arbiter.MultiplePortReceive<T0>(bool persist, Port<T0> [] ports, VariableArgumentHandler<T0> handler);
  • 16. Example: Hello World! in Math (Matrix Multiplication)  From site: Scalar and Matrix Multiplication
  • 17. Data Flow Diagram portMatrix1 portMatrix2 portSum portResult Result + Multiply * Sum handler handler  Simplified graphical representation of the data flow in the Matrix multiplication example
  • 18. Example: racing conditions  STOP! There is a catch!  Change the number of threads for the Dispatcher to 0 (it’ll use a default number of worker threads)  Result is changing all the time  Dispatcher is providing a real scheduling of work items across multiple CPUs and Threads  Order is unpredictable !!! Never count on it !!!
  • 19. Common Arbiters  single item receivers for specifying handlers on a single port  a choice arbiter which will chose which of two receivers to fire based on the availability of messages  an interleave arbiter (explained later)  a join arbiter for static join expressions  MultipleItemReceive arbiters for specifying dynamic joins
  • 20. Predefined Arbiters (partial list)  FromHandler  Just executes a method (not associated with a port)  FromIteratorHandler  Execute until enumerator is done (not associated with a port)  Receive  Process a single item from a port  MultipleItemReceive  Process a bunch of items at once  MultiplePortReceive  Process a single item from multiple ports (one item per port)  JoinedReceive  Process multiple items from 2 ports (one item per port)  Choice  Executes one & only one method from a set of methods  Interleave  Calls back a set of methods to process items from various ports. Arbiter is similar to a reader/writer thread synchronization lock
  • 21. Choice Arbiter Handler Arbiter.Choice(PortSet<T0, T1> resultPort, Handler<T0> h0, Handler<T1> h1); Arbiter.Choice(params ReceiverTask[] receivers);  The choice arbiter allows one to specify that one of two (or more) branches should fire and the others should be discarded. For example using the first method:  Example: Arbiter.Activate(taskQueue, Arbiter.Choice( Arbiter.Receive(false, port1, MyIntHandler), Arbiter.Receive(false, port2, MyStringHandler) ) ); Will run either MyIntHandler or MyStringHandler but not both. The choice will be determined by the availability of int or string message on the ports and if both types of messages are available then a non-deterministic choice is made.
  • 22. Join Arbiter Handler  Arbiter.Activate(dispatcherQueue, Arbiter.JoinedReceive<int,string>(true, p1,p2, IntAndStringJoinedHandler) );  The above will schedule the execution of the IntAndStringJoinedHandler when values can be atomically read on ports p1 AND p2 and will continue doing so as long as messages are available (in this example its a persisted receiver). The handler will be passed the values that were read. One can join over several ports of different types.  MultiportReceive is a form of a Join Arbiter: Arbiter.MultiplePortReceive<T0>(bool persist, Port<T0> [] ports, VariableArgumentHandler<T0> handler);
  • 23. Handler Interleave Arbiter Handler Handler  Arbiter.Interleave( TeardownReceiverGroup teardownGroup, ExclusiveReceiverGroup exclusiveGroup, ConcurrentReceiverGroup concurrentGroup );  Expresses concurrent calculations  Corresponds to multiple reads but single writers to a shared state. Its a more high level, far more concise way to capture advanced protection schemes.  The one time (non-persistent) shutdown handler (any one from the TeardownReceiverGroup) will cause the entire interleave to stop, guaranteeing no delegates are running or will ever run again. Makes clean up easy!  Why not to use join?  Interleave is error prone for this kind of operations.
  • 24. Interleave Arbiter: continues  Teardown will occur when all handlers have stopped executing (it has strong guarantees). It will not wait until all queued messages have executed, only just when all handlers currently running are done. At least that is the intent.  The interleave arbiter is biased towards exclusive handlers and the teardown group, so any more queued messages will not be processed the moment an exclusive or teardown message is received.
  • 25. Iterators: no more CPS  Arbiter.Activate(dq, Arbiter.FromIteratorHandler(SaveWebSiteToFile)); IEnumerator<ITask> SaveWebSiteToFile() { … }  Arbiter.Activate(dq,Arbiter.ReceiveWithIterator(false,port,DoWorkHandler)); IEnumerator<ITask> DoWorkHandler(DoWork w) { … }  Inheriting from the IEnumerator interface allows one to specify "yield" points in a method at which control flow returns to the caller. When a MoveNext() method is called on such a method control flow resumes from the “yield” point, not from the start of the method.  The coordination primitives in CCR all inherit from the ITask interface and this is used to help identify the iteration variable for use with the IEnumerator interface.
  • 26. Iterator: example public void Start() { Arbiter.Activate(taskQueue, Arbiter.ReceiveWithIterator(false, pMain, DoWorkHandler)); } IEnumerator<ITask> DoWorkHandler(DoWork w) { DoWork workA = new DoWork(); Result r = null; // send message to ServiceA pServiceA.Post(workA); // yield for result on response port attached to outbound message yield return Arbiter.Choice(workA.pResponse, delegate (Result Res) { r = Res;}, delegate (Failure F) { Trace.WriteLine("Failed");} ); // when either branch above happens, we will continue executing // here without ever having blocked a thread! if (r == null) yield break; // error occurred, break iteration // send next message, depending on the result from A DoWork workB = new DoWork(r); pServiceB.Post(workB); // ... handle result form B etc. }
  • 27. More on iterators  Schedule a task that will iterate over some message coordination dispatcherQueue.Enqueue(new IterativeTask<int>(message, MyIntIterator)); IEnumerator<ITask> MyIntIterator(int message) { Console.WriteLine(“got: {0}”, message); yield break; }  You can also associate a Reissue receiver with a port and an iterator Handler Arbiter.Activate(dispatcherQueue, Arbiter.ReceiveWithIterator(true, port, DoWorkHandler));
  • 28. Enumerator Handler limitations  static IEnumerator<ITask> Handler() { yield return Arbiter.FromHandler(delegate() { Console.WriteLine("I got here..."); }); yield break; } BAD!  You can’t yield to any handler. You must yield to a receive, a choice or a join (or multiple item receive).  This is a limitation of the current version of the CCR. To get around this you can of course create a simple port, post and then yield return: Port<bool> port = new Port<bool>(); port.Post(true); yield return Arbiter.Receive(false,port,delegate(bool b){ … });
  • 29. Don’t starve  Very hard to locate a blocked or misbehaving thread in the pool (very easy in GUI – only one thread)  System.Threading.Timer is a convenient way to shoot yourself in the foot – all instances are using the same thread pool (size: 50)  Few simple guidelines to avoid starvation:  Avoid using blocking I/O in an event handler.  Split individual, long-running computations into several shorter ones.  Choose useful intervals for timer-driven behavior.  Serialize timer events of the same activity.
  • 30. Timeouts – don’t hang forever  Never forget about Timeouts  Tell the DispatcherQueue to wait and then to post the current date and time into the timeoutPort: Port<DateTime> timeoutPort = new Port<DateTime>(); dq.EnqueueTimer(TimeSpan.FromMinutes(2), timeoutPort); Arbiter.Receive(false, timeoutPort, delegate(DateTime dt) { // … do stuff … });
  • 31. Predicates = filters  A sample equal thousand words:  Port<int> Port = new Port<int>(); Arbiter.Activate(taskQueue, Arbiter.Receive(true, Port, HandlerThatRunsOnlyWithLargeInts, MyLargeIntegerFilter), Arbiter.Receive(true, Port, HandlerThatRunsOnlyWithSmallInts, MySmallIntegerFilter), Arbiter.Receive(true, Port, MyCatchAllIntHandler)); bool MyLargeIntegerFilter(int i) { if (i> 1000000) return true; else return false; }
  • 32. Web Crawler – problem definition  Create a smart web crawler that will download images and the pages themselves recursively from the web.  Flush the downloaded content to your hard drive.  Download requests should timeout if hanged.  Code should be 100% asynchronous.
  • 33. Web Crawler – non-goals  Limit the depth of the recursion with a configurable parameter.  Download only pages descendants of the root site.  Save each page (and all its images) into it’s own folder.  Preserve the relationship of the pages, while writing to the disk, as nested folders.  Show the progress on the Windows form without affecting the user’s experience (non- blocking display).
  • 34. Web Crawler – the strategy  Provide a continuous stream of URLs  Interleave?  FromIteratorHandler?  Better: persistent Receive handler  Each URL request will either succeed, fail or timeout  Definitely the Choice arbiter with timeout port  As soon as download completed – schedule the asynchronous write  Choice arbiter – success or failure
  • 35. Web Crawler – code & demo YES !!! Unbelievable !!! IT WORKS!!! IT’S EASY!!!
  • 36. What about WinForms?  Use Microsoft.Ccr.Adapters.WinForms  ManualResetEvent MainThreadEvent = new ManualResetEvent(false); // Bind dispatcher queue to WinformsAdaptor WinFormsServicePort port = WinFormsAdapter.Create(dispatcherQueue); port.Post(new RunForm(delegate { form = new WebCrawlerForm(port); form.HandleDestroyed += delegate(object sender, EventArgs e) { MainThreadEvent.Set(); }; return form; })); // Wait for a “shutdown” signal MainThreadEvent.WaitOne(); // We need to inform the WinFormsAdaptor that it is about to quit. port.Post(new Shutdown()); // Let the system to finalize everything System.Threading.Thread.Sleep(500);
  • 37. Causality ~ <try/catch>  Causalities are a generalization of try/catch, across threads and processors, of the nested exception handling mechanism. Much more powerful however since it can deal with Joins (two different causalities coming together in a common handler).  They are NOT transactions  When an exception is thrown, within any logically related descendant of a Post operation, that exception can be cleanly caught and dealt within one place.  The CoordinationPort allows anyone within a causality to post a message to the "owner" of the causality, allowing you to implement all kinds of internal communication protocols.
  • 38. Causality: example  Port<Exception> pException = new Port<Exception>(); Arbiter.Activate(dispatcherQueue, Arbiter.Receive(false, pException, /* ExceptionHandler */ delegate(Exception ex) { System.Diagnostics.Trace.WriteLine(ex.ToString()); })); Arbiter.Activate(dispatcherQueue, Arbiter.FromHandler(delegate { // Define Causality scope (owner) Dispatcher.AddCausality(new Causality("test", pEx)); // … do some stuff … that spawn AsynchronousHandler … } void AsynchronousHandler()  { // … do some more stuff that throws exception throw new Exception(“bad things happen …”); }
  • 39. Advanced CCR: the next steps  The observer pattern (what is called pub/sub or publication/subscription) can be implemented using the Subscription service. The service (implemented using the CCR) keeps a list of ports, and then posts the message N items (one for each subscriber). Service’s can be observed, used across nodes/machines. This keeps the CCR simple.  See Service Tutorials 4,5,6 for more info.  If a service is overkill in your scenario, you can write a simple class that does this: keeps a list of ports and replicates messages on them. Or you can write a simple arbiter (derive from Receiver) that does this.  Service orchestration …
  • 40. Meet BOB (version 1)  Robot (self programmable), controlled by the CCR (running on Mobile device - PDA)  Communicates with a main computer to upload gathered information and to get new instructions
  • 41. MS Robotics Studio (MSRS)  Writing an application using Microsoft Robotics Studio is a simple matter of orchestrating input and output between a set of services. Services represent the interface to software or hardware and allow you to communicate between processes that perform specific functions.
  • 42. Simulation Runtime  Simulation runtime can be used in a variety of advanced scenarios with high demands for fidelity, visualization and scaling. At the same time a novice user can use simulation with little to no coding experience and develop interesting applications.
  • 43. VPL – Visual Programming Language  Application development environment designed on a graphical dataflow-based programming model
  • 44. Conclusion  The CCR is a CLR library that provides a consistent and scalable way to program asynchronous operations and coordinate among multiple responses.  Framework Class Library (FCL) classes, that already support the CLR's asynchronous programming model (such as Stream's BeginRead and BeginWrite methods) can be easily wrapped, allowing existing types to integrate with the CCR so that complex failure handling and coordination patterns can be coded in a robust, reliable and concise way.  The use of C# iterators for scheduling operations allows sequential programming without blocking OS threads, thus enabling scaling without sacrificing the simplicity of sequential code.
  • 45. Acronyms  CCR – Concurrency and Coordination Runtime  APM – Asynchronous Programming Model  CPS – Continuous Passing Style  CLR – Common Language Runtime  FCL – Framework Class Library  MSRS – Microsoft Robotics Studio
  • 46. Links  CCR Wiki http://channel9.msdn.com/wiki/default.aspx/Channel9.ConcurrencyRuntime  CCR Patterns http://channel9.msdn.com/wiki/default.aspx/Channel9.CcrPatterns  MSRS Home http://msdn.microsoft.com/robotics/  My e-mail: igormoochnick@yahoo.com  My new Blog: http://igorshare.blogspot.com/  My new Web Site: http://igor.moochnick.googlepages.com/