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

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020