Search code examples
c#scalaparallel-processingactorasync-await

Examples of C# 5.0 async/await vs. Akka actors vs. basic fork/join?


Both C# and Scala have adopted frameworks for simplifying doing asynchronous/parallel computation, but in different ways. The latest C# (5.0, still in beta) has decided on an async/await framework (using continuation-passing under the hood, but in an easier-to-use way), while Scala instead uses the concept of "actors", and has recently taken the actors implementation in Akka and incorporated it into the base library.

Here's a task to consider: We receive a series of requests to do various operations -- e.g. from user input, requests to a server, etc. Some operations are fast, but some take awhile. For the slow ones, we'd like to asynchronously do the operation (in another thread) and process it when the thread is done, while still being free to process new requests.

A simple synchronous loop might be (pseudo-code):

while (1) {
  val request = waitForAnything(user_request, server_request)
  val result = do_request(request)
  if (result needs to be sent back)
    send_back_result(result)
}

In a basic fork/join framework, you might do something like this (pseudo-code):

val threads: Set[Thread]

while (1) {
  val request = waitForAnything(user_request, server_request, termination of thread)
  if (request is thread_terminate) {
    threads.delete(request.terminated_thread)
    val result = request.thread_result
    if (result needs to be sent back)
      send_back_result(result)
  } else if (request is slow) {
    val thread = new Thread(() => do_request(request))
    Threads.add(thread)
    thread.start()
  } else {
    val result = do_request(request)
    if (result needs to be sent back)
      send_back_result(result)
  }
}

How would this look expressed using async/await and using actors, and more generally what are the advantages/disadvantages of these approach?


Solution

  • Please consider mine as a partial answer: "old" Scala actors have been replaced by Akka actors , which are much more then a simple async/await library.

    1. Akka actors are "message-handlers" which are organized into a hierarchy which can be running on one or more JVMs and even distributed across a network.
    2. When you realize your asynchronous processing requires actors (read later why this is not forcely necessary), Akka let you and helps you to put in place the best patterns in terms of failure handling, dispatching and routing
    3. Akka comes with different transport layers, and other fancies ready-to-use facilities such as explicit Finite State Machines, Dataflow concurrency and others.
    4. Akka comes with Futures, which are more likely to corresponds to the Async/Await framework in C# 5.0

    You can read more about Akka futures on the Akka website or on this post:

    Parallel file processing in Scala