Fixing TPL Using Responsive Tasks:

October 28, 2021 · View on GitHub

NOW MAUI READY !!!

Fixing TPL Using Responsive Tasks:

TPL: The Promise

When Microsoft announced the Task Parallel Library, C# programmers everywhere rejoiced. Simplified threads? Error handling within the library itself? What could possibly go wrong?

Just about everything, as it turns out.

A task requires a root in order to be properly awaited. For instance:

// An awaitable task
public Task YouCanAwaitMe() { }

// A root where you an await a task
public async Task IWillAwait()
{
   await YouCanAwaitMe().WithoutChangingContext();
}

TPL: The Reality

Unfortunately, a Xamarin app doesn't have any valid roots. For instance, not at:

  • Constructors
  • Content changed
  • Binding context changed
  • Event handlers
  • Global messages
  • Overrides
  • Property Setters

Any location that fails to provide a Task signature is a false root. This causes unsafe results:

public class FalselyRootedView : ContentView
{
   protected override async void OnBindingContextChanged()
   {
      base.OnBindingContextChanged();
      
      // Mega hack -- called from a void method (illegal!)
      await StartUpViewModel().WithoutChangingContext();
   }
   
   public virtual Task StartUpViewModel()
   {
      return Task.CompletedTask;
   }
}

// Derive and consume the falsely rooted view as if it were valid
public class FalseConsumer : FalselyRootedView
{
   pubic override async Task StartUpViewModel()
   {
      // Everything seems OK from this perspective, but this task can proceed at any time and 
      //    without our control; it was never properly awaited.  Anything relying on it will 
      //    accelerate into a race condition; variables will not be set on time; nothing can 
      //    be relied upon in a predictable order.
      await SomeOtherTask().WithoutChangingContext();
   }
}

Until Microsoft converts all current code signatures to Tasks, programmers are stuck using these sorts of risky mechanisms.

Responsive Tasks is tested and proven

See the unit tests.

Index

Each page describes a problem and its Responsive solution:

Part 1 of N: Pages, Views & View Models

Part 2 of N: Events & Messaging

Part 3 of N: Technical Guide

Part 4 of N: Button Pressed: Closing the Final TPL Gaps

Part 5 of N: Proofs

ResponsiveTasks Is Open Source; Enjoy Our Entire Public Suite

Shared Utils (MAUI Ready!)

GutHub

NuGet

The Smart DI Container (MAUI Ready!)

GutHub

NuGet

Responsive Tasks (MAUI Ready!)

GutHub

NuGet

PlatformIndependentShared (MAUI Ready!)

GutHub

NuGet

UI.XamForms

GutHub

NuGet

The Modern App Demo

GutHub