Menu

Async-Await and Actor rules!

asy proger

Since C# Version 5 has been released in Visual Studio 2012 we may use the new keywords async and await.
It is a great way to write asynchronous programs without clumsy callback delegates or lambdas.
It allows to coordinate several asynchronously running tasks as it was not possible before.

I already mentioned some points and gave some links about async await in [Concept of AsyncWcfLib] and [Threadsafety and SynchronizationContext].

Apart from using async-await I recommend to adopt an actor based design (see [Actors]) in order to get fast, reliable, responsive and distributed applications.
The following guiding rules will help in praxis to reach the goal.

  • Always use threads with synchronization context and be careful not to start a threadpool thread.
    This way you can write a single threaded, lock-free actor.

  • Public methods and properties of your actor main class must be threadsafe.
    Especially IActorInput and IActorOutput are intended for public exposure.

  • Do not pass object references from one actor to another.
    Actors run on different threads and may not access each others data.
    Only sending of messages between actors is allowed.
    A sent message and all its members may not be accessed by the sender anymore (unless the message member is immutable).

  • Bring data of your actor in a consistant state before calling 'await'.
    Code between two await statements run as atomic, uninterruptable code segments.
    At each await, the scheduler may run other tasks of your actor on your thread.
    To be exact, the awaited async method will be executed synchronously until another await inside the method is hit.
    The scheduler runs other tasks only when really something has to be awaited.
    see http://msdn.microsoft.com/en-us/magazine/hh456403.aspx
    and http://blogs.msdn.com/b/pfxteam/archive/2012/04/12/10293335.aspx

  • Keep versioning in mind when sending messages over the network.
    The Version of the partners message assembly is accessible in every response you get from it (WcfReqIdent.Sender.CifVersion).
    For large systems you probably need some backward/forward version tolerance.
    Do not change message class and member names, you may use name-attributes for the serializer.
    Do not add enum members in later versions, you may serialize enums as int and write a property to get the enum range checked.
    Specially handle the default value 0. It will be set, when a member has not been serialized by an older network partner.


Related

Wiki: Actors
Wiki: Concept of AsyncWcfLib
Wiki: Home
Wiki: Threadsafety and SynchronizationContext

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.