hits counter

A Synchronization Context Based On The TPL Dataflow Library

The purpose of the synchronization model implemented by the SynchronizationContext class is to allow the asynchronous/synchronization operations of the common language runtime to behave properly with different synchronization models. This model also simplifies some of the requirements that managed applications have to follow in order to work correctly under different synchronization environments. Examples of such synchronization environments are user interface infrastructures like Windows Forms, Windows Presentation Foundation and ASP.NET.

Providers of synchronization models extend this class to provide their own implementations. Because these user interface infrastructures usually run on their own threads, dispatching execution to their execution contexts usually means leaving the current thread.

The Task Parallel Library (TPL) provides dataflow components to help increase the robustness of concurrency-enabled applications. These dataflow components are collectively referred to as the TPL Dataflow Library. This dataflow model promotes actor-based programming by providing in-process message passing for coarse-grained dataflow and pipelining tasks. The dataflow components build on the types and scheduling infrastructure of the TPL and integrate with the C#, Visual Basic, and F# language support for asynchronous programming. These dataflow components are useful when you have multiple operations that must communicate with one another asynchronously or when you want to process data as it becomes available.

The TPL Dataflow Library (System.Threading.Tasks.Dataflow namespace) is not distributed with the .NET Framework 4.5. To install the System.Threading.Tasks.Dataflow namespace, open your project in Visual Studio 2012, choose Manage NuGet Packages from the Project menu, and search online for the Microsoft.Tpl.Dataflow package.

Sometimes, for demo or testing purposes, I need a synchronization context that behaves like the user interface ones but doesn’t force me to build applications with a user interface and the TPL Dataflow Library seemed like a good option to implement such synchronization context.

It was as easy as this:

public class TplDataflowSynchronizationContext : SynchronizationContext
{
    private ActionBlock<ActionItem> ab
        = new ActionBlock<ActionItem>(
            item =>
            {
                Trace.WriteLine(
                    string.Format("{0}: {1}", Environment.CurrentManagedThreadId, item.operation));
            </span><span style="background: white; color: blue">try
            </span><span style="background: white; color: black">{
                item.d(item.state);
            }
            </span><span style="background: white; color: blue">finally
            </span><span style="background: white; color: black">{
                item.SetResult(</span><span style="background: white; color: blue">true</span><span style="background: white; color: black">);
            }
        });

</span><span style="background: white; color: blue">public override </span><span style="background: white; color: #2b91af">SynchronizationContext </span><span style="background: white; color: black">CreateCopy()
{
    </span><span style="background: white; color: blue">return new </span><span style="background: white; color: #2b91af">TplDataflowSynchronizationContext</span><span style="background: white; color: black">();
}

</span><span style="background: white; color: blue">public override void </span><span style="background: white; color: black">Post(</span><span style="background: white; color: #2b91af">SendOrPostCallback </span><span style="background: white; color: black">d, </span><span style="background: white; color: blue">object </span><span style="background: white; color: black">state)
{
    </span><span style="background: white; color: #2b91af">Trace</span><span style="background: white; color: black">.WriteLine(
        </span><span style="background: white; color: blue">string</span><span style="background: white; color: black">.Format(</span><span style="background: white; color: #a31515">"{0}: Posting..."</span><span style="background: white; color: black">, </span><span style="background: white; color: #2b91af">Environment</span><span style="background: white; color: black">.CurrentManagedThreadId));

    </span><span style="background: white; color: blue">this</span><span style="background: white; color: black">.ab.Post(</span><span style="background: white; color: blue">new </span><span style="background: white; color: #2b91af">ActionItem </span><span style="background: white; color: black">{ d = d, state = state, operation = </span><span style="background: white; color: #a31515">"Post" </span><span style="background: white; color: black">});

    </span><span style="background: white; color: #2b91af">Trace</span><span style="background: white; color: black">.WriteLine(
        </span><span style="background: white; color: blue">string</span><span style="background: white; color: black">.Format(</span><span style="background: white; color: #a31515">"{0}: Posted."</span><span style="background: white; color: black">, </span><span style="background: white; color: #2b91af">Environment</span><span style="background: white; color: black">.CurrentManagedThreadId));
}

</span><span style="background: white; color: blue">public override void </span><span style="background: white; color: black">Send(</span><span style="background: white; color: #2b91af">SendOrPostCallback </span><span style="background: white; color: black">d, </span><span style="background: white; color: blue">object </span><span style="background: white; color: black">state)
{
    </span><span style="background: white; color: #2b91af">Trace</span><span style="background: white; color: black">.WriteLine(
        </span><span style="background: white; color: blue">string</span><span style="background: white; color: black">.Format(</span><span style="background: white; color: #a31515">"{0}: Sending..."</span><span style="background: white; color: black">, </span><span style="background: white; color: #2b91af">Environment</span><span style="background: white; color: black">.CurrentManagedThreadId));

    </span><span style="background: white; color: #2b91af">ActionItem </span><span style="background: white; color: black">item = </span><span style="background: white; color: blue">new </span><span style="background: white; color: #2b91af">ActionItem </span><span style="background: white; color: black">{ d = d, state = state, operation = </span><span style="background: white; color: #a31515">"Send" </span><span style="background: white; color: black">};
    </span><span style="background: white; color: blue">this</span><span style="background: white; color: black">.ab.SendAsync(item);
    item.Task.Wait();

    </span><span style="background: white; color: #2b91af">Trace</span><span style="background: white; color: black">.WriteLine(
        </span><span style="background: white; color: blue">string</span><span style="background: white; color: black">.Format(</span><span style="background: white; color: #a31515">"{0}: Sent."</span><span style="background: white; color: black">, </span><span style="background: white; color: #2b91af">Environment</span><span style="background: white; color: black">.CurrentManagedThreadId));
}

</span><span style="background: white; color: blue">public class </span><span style="background: white; color: #2b91af">ActionItem </span><span style="background: white; color: black">: </span><span style="background: white; color: #2b91af">TaskCompletionSource</span><span style="background: white; color: black">&lt;</span><span style="background: white; color: blue">bool</span><span style="background: white; color: black">&gt;
{
    </span><span style="background: white; color: blue">public </span><span style="background: white; color: #2b91af">SendOrPostCallback </span><span style="background: white; color: black">d;
    </span><span style="background: white; color: blue">public object </span><span style="background: white; color: black">state;
    </span><span style="background: white; color: blue">public string </span><span style="background: white; color: black">operation;
}

}

UPDATE:

Fixed implementation because the SynchronizationContext.Send method returned without having completely executed the operation. Thanks to Svick for pointing that out and Stephen Toub for the help fixing it.

No Comments