Asynchronous Thread Safety, the Easy Way in .Net 4.5

ConcurrentExclusiveSchedulerPair is a new task scheduler introduced in framework 4.5 to provide thread safety by scheduling updates or read operation to occur in the future when it’s safe to do so.

 

The scheduler could allow read style operations to occur in concurrently while update operations are scheduled until its safe to perform. Consider this student class for example;

public class Student
 {
     public Student(int totalClasses, int totalGrades)
     {
         this.totalGrades = totalGrades;
         this.classesCount = totalClasses;
     }
     int classesCount ;
     int totalGrades;
     readonly ConcurrentExclusiveSchedulerPair scheduler = 
             new ConcurrentExclusiveSchedulerPair();
     public Task<int> TotalGrades
     {
         get
         {
             return Task.Factory.StartNew(()=>totalGrades,
                     CancellationToken.None, 
                     TaskCreationOptions.None,
                     scheduler.ConcurrentScheduler);
         }
     }
     public Task<int> CalculateAverage
     {
         get
         {
             return Task.Factory.StartNew(
                 ()=>classesCount /totalGrades,
                 CancellationToken.None,
                 TaskCreationOptions.None,
                 scheduler.ExclusiveScheduler);
 
         }
     }
     public Task AddGrade(int grade)
     {
         return Task.Factory.StartNew(()=> totalGrades+=grade,
             CancellationToken.None, 
             TaskCreationOptions.None,
             scheduler.ExclusiveScheduler);
         
     }
 
 
 }

Each instance of this Student class has its own scheduler when any request is made against the instance of the class; the operation is executed asynchronously using the appropriate scheduler. Read only operations like TotalGrades use a concurrent schedule, and write operations use the Exclusive scheduler. The exclusive scheduler ensures only one thread can change the object state one at a time.

Comments (2) -

Can I use Task.Run instead of Task.Factory.StartNew ?

Michael,
Unfortunately No, Task.Run doesn't have any overload that accepts a Scheduler.
You may have to be able to write your own TaskFactory and role out your own version of Task.Run

Add comment