Home > Articles > Home & Office Computing > Microsoft Windows Desktop

  • Print
  • + Share This
This chapter is from the book

WF Threads

From the point of view of activities, the WF runtime makes no guarantee about which CLR thread is used to dispatch a work item in a scheduler work queue. It is possible for any two work items, even consecutively enqueued work items, to be dispatched using different threads.

It is the application hosting the WF runtime that decides how CLR threads are to be allocated to WF program instances (though the WF runtime does impose a limit of one thread at a time for a specific WF program instance). It is also solely the host application that determines when a WF program instance should be passivated. Typically, passivation occurs when a WF program instance becomes idle, but it is possible, as we will see in Chapter 5, for a WF program instance to be passivated even when its scheduler work queue is not empty. As a developer of activities, the safest assumption is that every work item is dispatched on a different thread. Although in practice the same CLR thread will be used to dispatch a set of work items, it is best to not make any assumption about the CLR thread on which activity methods are invoked. This means not storing data in the thread context or call context or, more generally, not relying on Thread.CurrentThread in any way.

The WF runtime does guarantee that the scheduler managing the work items for a single WF program instance utilizes exactly one CLR thread at a time, for a given episode of the WF program instance. In other words, the scheduler never performs concurrent dispatch of work items in its work queue. Dispatch always occurs one item at a time. Furthermore, the WF runtime never preempts the execution of a dispatched work item. Activities are counted upon to employ bookmarks when they are logically blocked, allowing them to yield the CLR thread while they await stimulus.

The fact that the WF runtime uses a single CLR thread at a time for a given WF program instance is a pragmatic decision. It is possible to imagine concurrent dispatch of work items, but the benefits appear to be outweighed by the drawbacks.

One big advantage of a single-threaded execution model is the simplification of activity development. Activity developers need not worry about concurrent execution of an activity's methods. Locking, preemption, and other aspects of multithreaded programming are not a part of WF activity development, and these simplifications are important given WF's goal of broad adoption by .NET developers.

Some readers might object to the fact that the threading model of the WF runtime eliminates the possibility of true, or fine-grained, concurrency (the simultaneous use of more than one machine processor). Let's be clear: What is precluded is the possibility of true concurrency within an instance of a WF program. In any application where the number of simultaneously executing (non-idle) WF program instances tends to be greater than the number of machine processors, true concurrency would not buy you much. The design-time overhead of a vastly more challenging programming model for activities weighs down this approach, and mightily so in our estimation. Computations that benefit from true concurrency are, for WF programs, best abstracted as features of a service; the service can be made available to activities (using the service chaining techniques we've already described). In this way, the service can be executed in an environment optimized for true concurrency, which may or may not be on the machine on which the WF program instance is running.

True concurrency is a rather simple concept to describe, but the techniques for synchronization that are available in most mainstream programming paradigms are difficult to master and, when not applied properly, are notorious for causing hard-to-find bugs that make programs defective (or, perhaps, in the eyes of their users, capricious). The WF programming model arguably has found a sweet spot, given the types of problems that WF is intended to solve. WF program instances clearly allow interleaved (pseudo-concurrent) execution of activities, and WF makes it easy to write and use the constructs that permit interleaving. We have seen an example of such an activity, Interleave, and how essentially similar it is to Sequence, in both its implementation and its usage in a WF program.

Just like the CLR virtualizes a set of operating system threads, the WF runtime can be said to virtualize CLR threads. The interleaved execution of activities within a WF program instance is therefore not unlike the interleaved execution of CLR threads within an operating system process. Each child activity of an Interleave can be thought of as executing on a separate WF thread, though in fact this WF thread is a purely conceptual entity and does not have any physical manifestation in the WF programming model. Figure 3.22 depicts the relationship between these shadowy WF threads and actual CLR threads.

Figure 3.22

Figure 3.22 WF threads

This pattern of execution is sometimes called pseudo-concurrency or perceived parallelism.

Synchronized Access to State

Given the WF runtime's threading model, it should be clear that the synchronization primitives used in C# programs are not applicable in WF programs.

Synchronization primitives are not aware of the interleaved execution of WF threads. In fact, they can get you into quite a bit of trouble in a WF program and should be generally avoided. For example, if two activities in a WF program refer to some shared state (for instance, several fields of a third activity, accessed as properties of that activity), then CLR synchronization techniques will not be the right choice for ensuring synchronized access to the shared state. CLR locking primitives are generally not designed to survive and remain valid across passivation cycles of a WF program instance.

Put another way, since the WF programming model virtualizes threads of program execution, it must also carry the burden of providing synchronized access to shared data.

WF provides the ability to synchronize access to state shared by multiple WF threads in terms of a special composite activity defined in the System.Workflow.ComponentModel namespace. This activity is named SynchronizationScopeActivity and it executes its child activities sequentially.

SynchronizationScopeActivity is the WF programming model's synchronization primitive. It allows the developer of a WF program to draw boundaries around synchronization domains of (pseudo)concurrently executing activities, which, conceptually, run on different WF threads.

The SynchronizationScopeActivity type is shown in Listing 3.20.

Listing 3.20. SynchronizationScopeActivity

namespace System.Workflow.ComponentModel
{
  public sealed class SynchronizationScopeActivity : CompositeActivity
  {
    public ICollection<string> SynchronizationHandles { get; set; }

    /* *** other members *** */
  }
}

As you can see, the SynchronizationScopeActivity type carries a property called SynchronizationHandles of type ICollection<string>. This property holds a set of named synchronization handles. A synchronization handle is essentially a locking primitive.

The WF runtime guarantees that occurrences of SynchronizationScopeActivity sharing a synchronization handle token will be executed serially without any interleaving of their contained activities. In other words, one Synchronization ScopeActivity will complete before the next one (that shares a synchronization handle with the first) begins. To avoid deadlocks, the WF runtime internally manages virtual locks (not CLR locks) corresponding to the synchronization handles specified by the occurrences of SynchronizationScopeActivity in a WF program. These virtual locks survive passivation of the WF program instance.

Before the execution of a SynchronizationScopeActivity begins, all of the virtual locks associated with that SynchronizationScopeActivity activity's set of synchronization handles are obtained.

Listing 3.21 shows a WF program that uses SynchronizationScopeActivity to provide synchronized execution of interleaving activities. Even though there is no actual shared data, the two occurrences of SynchronizationScopeActivity require the same virtual lock and therefore execute serially.

Listing 3.21. Synchronization Using SynchronizationScopeActivity

<Interleave xmlns="http://EssentialWF/Activities"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wf="http://schemas.microsoft.com/winfx/2006/xaml/workflow" >
  <wf:SynchronizationScopeActivity SynchronizationHandles="h1">
    <WriteLine x:Name="w1" Text="One"/>
    <WriteLine x:Name="w2" Text="Two"/>
  </wf:SynchronizationScopeActivity>
  <wf:SynchronizationScopeActivity SynchronizationHandles="h1">
    <WriteLine x:Name="w3" Text="Three"/>
    <WriteLine x:Name="w4" Text="Four"/>
  </wf:SynchronizationScopeActivity>
</Interleave>

This WF program will always produce one of the following outputs:

One

Three

Two

Four

Three

One

Four

Two

There are only two possible outputs for the preceding program. The Interleave activity will schedule both of the SynchronizationScopeActivity activities. Whichever one is scheduled first acquires the virtual lock that protects the synchronization handle "h1". Once the lock is obtained, the second SynchronizationScopeActivity activity is not allowed to execute, even though it has a work item in the scheduler work queue. Only when the first SynchronizationScopeActivity transitions to the Closed state will the lock be released, and the second SynchronizationScopeActivity be permitted to execute.

In the preceding example, there is no interleaving of activity execution across the two occurrences of SynchronizationScopeActivity, due to the fact that they require the same lock. If we change the program by altering the value of the SynchronizationHandles property for one SynchronizationScopeActivity to "h2", then the presence of the two SynchronizationScopeActivity activities is meaningless because they are defining different synchronization domains. Interleaved execution of the activities contained within them can and will occur.

SynchronizationScopeActivity activities can be nested in a WF program. Each SynchronizationScopeActivity acts as a lock manager that is responsible for granting locks to its child activities and managing a wait list of activities waiting to acquire locks (the WF runtime acts as the lock manager for the root activity of the program).

SynchronizationScopeActivity, when it begins its execution, collects the locks corresponding to its synchronization handles as well as those for all nested SynchronizationScopeActivity activities.

Because a parent SynchronizationScopeActivity is guaranteed to start its execution before a SynchronizationScopeActivity nested within it, the parent acquires the locks needed for all of its nested child SynchronizationScopeActivity instances before executing them, and deadlocks are safely avoided.

For the WF program shown in Listing 3.22, either SynchronizationScope-Activity s1 or SynchronizationScopeActivity s4 will execute in its entirety before the other one begins executing. In this example, the locks required by s1 and s4 are the same (indicated by the synchronization handles "a", "b", and "c"). In fact, the execution of s1 and s4 will be serialized even if they share a single synchronization handle name in their respective subtrees.

Listing 3.22. Nested SynchronizationScopeActivity Declarations

<Interleave xmlns="http://EssentialWF/Activities"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:wf="http://schemas.microsoft.com/winfx/2006/xaml/workflow">
  <wf:SynchronizationScopeActivity x:Name="s1"
    SynchronizationHandles="a">
<Interleave x:Name="i1">
  <wf:SynchronizationScopeActivity x:Name="s2"
    SynchronizationHandles="b">
    <WriteLine x:Name="w3" Text="One"/>
    <WriteLine x:Name="w4" Text="Two"/>
  </wf:SynchronizationScopeActivity>
  <wf:SynchronizationScopeActivity x:Name="s3"
    SynchronizationHandles="c">
    <WriteLine x:Name="w5" Text="Three"/>
    <WriteLine x:Name="w6" Text="Four"/>
   </wf:SynchronizationScopeActivity>
 </Interleave>
</wf:SynchronizationScopeActivity>
<wf:SynchronizationScopeActivity x:Name="s4"
  SynchronizationHandles="c">
  <Interleave x:Name="i2">
    <wf:SynchronizationScopeActivity x:Name="s5"
      SynchronizationHandles="b">
      <WriteLine x:Name="w9" Text="Five"/>
      <WriteLine x:Name="w10" Text="Six"/>
    </wf:SynchronizationScopeActivity>
    <wf:SynchronizationScopeActivity x:Name="s6"
      SynchronizationHandles="a">
      <WriteLine x:Name="w11" Text="Seven"/>
      <WriteLine x:Name="w12" Text="Eight"/>
    </wf:SynchronizationScopeActivity>
  </Interleave>
 </wf:SynchronizationScopeActivity>
</Interleave>

SynchronizationScopeActivity provides a simple way to synchronize the interleaved execution of WF threads. Effectively, this synchronization technique orders the dispatch of operations in the scheduler work queue in accordance with the synchronization domains that are named by SynchronizationScopeActivity activities.

  • + Share This
  • 🔖 Save To Your Account