28 posts categorized "Foundation"

04/07/2014

New Love for .NET and C#

At the Build 2014 conference, Microsoft showed new love for .NET. This blog post shows how Microsoft's love reveals.

WP_20140403_07_28_04_Pro

.NET Compiler Platform

The biggest thing for .NET is the .NET Compiler Platform ("Roslyn"). In development since the year 2009, Roslyn is nearing completion and has a new preview available.

Both C# and Visual Basic compilers are rebuilt using this compiler platform. What is the advantage of rebuilding the compiler when there are already working ones that have been implemented with native code?

For the Microsoft teams, this platform gives a clean architecture to evolve on. It's a lot easier to add features to C# and Visual Basic. Implementing a new features for these two languages doesn't mean the effort duplicated for every language, it can be done with just 1.2x instead of 2x. The effort to implementing new language features is a lot less compared to the older native C# compiler, as can be seen in the number of new features for C#.

For partners, it is a lot easier to create source-based tools and extensions for Visual Studio. Xamarin will use the .NET Compiler Platform in an upcoming edition. I also bet, tools like ReSharper will make use of this platform to create new features.

For developers, the .NET Compiler Platform gives a richer C# IDE experience. Coming with the preview you can already see smarter refactoring features. More to come :-)

Anders Hejlsberg demonstrated just three small changes in the code base for defining a new string literal. As the .NET Compiler Platform is open source, changes could be done by everyone. I just don't expect many to do their own C#. However using the .NET Compiler Platform it is easy to define guidelines for code styling, and easy allow for automatic code changes with preview of the changes shown.

Dustin Campbell demonstrated how easy it is to use the .NET Compiler Platform SDK to create a guideline for requiring braces with the block of if and else statements.

The preview can be downloaded from Microsoft Connect after registration.

.NET Foundation

The .NET Foundation was announced for faster open development and collaboration around many open source technologies for .NET. Among the projects in the foundation are the .NET Compiler Platform, ASP.NET MVC, ASP.NET Web API, Composition (MEF), ASP.NET SignarlR, Entity Framework, Rx (Reactive Extensions), Windows Azure .NET SDK, and also third party libraries such as Xamarin.Mobile, Xamarin.Auth, Couchbase for .NET, .NET Map Reduce API for Hadoop...

C# 6

Let's get into the history of C#. C# 2.0 offered generics with the language. C# 3 added LINQ and all the language features needed for LINQ such as Lambda expressions, type inference, anonymous types, and others. The theme of C# 4 was dynamic to make an easier integration with scripting languages and COM, offering the dynamic keyword, optional and named parameters. C# 5 was about async programming, just offering two new language keywords async and await. However, these small keywords again changed programming dramatically.

C# 6 is not about such a big change like generics, LINQ, or dynamic. However, it has many changes. With the .NET Compiler Platform, it is a lot easier to create new features. Thus many things that needed to wait with previous editions can be done now. Among the things that were shown at Build are primary constructors, declaration expressions, and indexed members.

Creating immutable types was always possible with .NET, but we had to write a lot of code. With the new language features, creating such types is possible reducing the code a lot.

New JIT Compiler, .NET Native

RyuJIT is a new JIT compiler for the .NET runtime. This compiler is a lot faster than the one now part of .NET. Rujit CTP 3 is available now. This version supports SIMD instructions (running the same operation on multiple data points simultaneously.

It gets even faster with .NET Native. 60% faster startup for Windows Store apps, and much smaller memory footprint. This product consists from a .NET Native compiler that makes use of a VC++ compiler backend and the .NET Native runtime (refactored and optimized CLR).

With Windows Store apps, it is still possible to upload MSIL app packages to the store. Later on the compiler in the cloud compiles the app in the store that is compiled for ARM and x64 architectures. x86 will follow.

Using this compiler also has the advantage that the compiler creates just one file containing native code for all libraries. Using IL code tools to analyze this code is no longer possible, it's native code.

Not only this, this compiler also creates just one file containing native code for all the libraries. Currently this native compiler is only available for Windows Store apps, but other technologies will follow.

Apps such as Wordament and Fresh Paint already make use of .NET Native and see great improvements.

Summary

With these developments I'm seeing really big steps forward with .NET. With many of these technologies it's just the beginning. For example, I can imagine big improvements in upcoming tools based on the .NET Compiler Platform. And then don't forget the new C# language features, .NET Native, RyuJIT, and the huge open source progress going on.

Another big thing for .NET are Universal Apps that I talk about in another blog post.

Christian

CN innovation

 

10/12/2012

Calling WinRT from Windows Desktop Apps

The .NET Framework is an API that can be used from server applications, Windows desktop applications, and is available for Windows Store apps. For Windows Store apps just a subset of the framework is available. The Windows Runtime (WinRT) is an API for Windows Store apps. However, some parts of it cannot be used from Windows Store apps, only from Windows desktop apps. The Visual Studio 2012 templates doesn’t give you a direct way to reference this runtime. This article shows how this can be done.

WinRT APIs

Some of the APIs from the Windows Runtime (WinRT) cannot be called from Windows Store apps, they are only available for Windows desktop apps. The documentation of the PackageManager class (namespace Windows.Management.Deployment) shows that this API is only available for desktop apps.

image

References with Windows Store Apps

Creating a Windows Store C# project, the Reference Manager shows a Windows category along with Assemblies, Solution, and Browse:

image

References with Windows Desktop Apps

Creating a desktop application, the Reference Manager lists Assemblies, Solution, COM, and Browse. The Windows category is missing.

image

The way how to add the missing Windows category cannot be found easily. I found it by comparing the project file of a Windows store application with the project file of a console application and found this missing TargetPlatformVersion element that needs to be defined within the PropertyGroup element.

    <TargetPlatformVersion>8.0</TargetPlatformVersion>

This element can be easily added from within Visual Studio by selecting the project in Solution Explorer, using the context menu Unload Project which gives a new context menu to edit the project file.

With the RTM version of Windows Store project templates, this element is no longer used. Maybe the project type GUIDs make the difference now. However, using the TargetPlatformVersion element is documented in the MSDN library. See Windows tab –> Extension Subgroup for more information.

With this change, the Windows tab is available in the Reference Manager:

image

There’s still something missing. Compiling code including the WinRT API gives clear errors that the System.Runtime assembly is missing. This assembly needs to be referenced. This assembly is not in the default list of assemblies in the Reference Manager, but you can browse for it in the directory C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\Facades, or add it directly to the project file.

image

Now the PackageManager from the Windows.Management.Deployment namespace together with the Package class from the Windows.ApplicationModel namespace can be used to show information about installed Windows Store apps.

      var pm = new PackageManager();
      IEnumerable<Package> packages = pm.FindPackages();
      foreach (var package in packages)
      {
        try
        {
          Console.WriteLine("Architecture: {0}", package.Id.Architecture.ToString());
          Console.WriteLine("Family: {0}", package.Id.FamilyName);
          Console.WriteLine("Full name: {0}", package.Id.FullName);
          Console.WriteLine("Name: {0}", package.Id.Name);
          Console.WriteLine("Publisher: {0}", package.Id.Publisher);
          Console.WriteLine("Publisher Id: {0}", package.Id.PublisherId);
          if (package.InstalledLocation != null)
            Console.WriteLine(package.InstalledLocation.Path);
          Console.WriteLine();
        }
        catch (FileNotFoundException ex)
        {
          Console.WriteLine("{0}, file: {1}", ex.Message, ex.FileName);
        }
      }

Thís API also requires administrative privileges, that’s why I’m adding an application manifest file to the project setting the level attribute of the requestedExecutionLevel element to requireAdministrator.

    <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
      <security>
        <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
          <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
        </requestedPrivileges>
      </security>
    </trustInfo>

Now the application runs successfully showing installed Windows Store apps.

More information about the Windows Runtime can be found in my new book Professional C# 2012, and of course in my workshops.

Christian

CN innovation

09/16/2011

C# Future Directions

Thursday at Windows Build Anders Hejlsberg presented the future directions of C#. The new version number of C# is 5. The major features on this version are the integration of the Windows Runtime (WinRT) and of course the already well known async and await keywords for asynchronous programming. Anders also talked about some other cool features that I’ll introduce here.

Async Programming

The preview of the async features for C# v5 are out for some time now. I’ve already shown these keywords in a blog article from last year. Deeper information on this will follow in upcoming blog articles. Anders also talked about some other cool features that I’ll introduce here.

Great news at the conference is that the WinRT API offers async versions of the API if the function needs more than 15ms. This are 10-15% of the methods of the API. These APIs only offer async versions. Functionality like file I/O, network I/O…

And async methods have a big place in the .NET Framework as well. This makes it a lot easier to write async applications. And all applications should use this! The user interface must be very very responsive.

WinRT API asynchronous methods use IAsyncOperation<T>, .NET methods Task<T>, and JavaScript promises.

Windows Runtime

The Windows Runtime is written natively. It’s a new version of COM. Using namespaces, classes, constructors, statics, events… Using it from  C# feels very natural. Although it’s implemented natively it nearly cannot be differentiated from C# calling into managed methods. The Windows Runtime team took a lot of features from .NET and added it to the native Windows API.

It’s similar easy to create C# types that can be used from any language making use of WinRT, e.g. JavaScript. Interop is made easy, no longer [DllImport] and COM Interop attributes. Just create a public C# type that is sealed and restricted to the types of the WinRT (or types that are mapped automatically like collection interface types). The method GetMovies() returning IAsyncOperation<IList<Movie>> can be called directly from JavaScript. For Task<T> can be easily converted to IAsyncOperation<T>.

Caller Info Attributes

C++ allows changing the code line numbers and filenames with __LINE__ and __FILE__ macros. Macros are not possible in C# and never will be. However, this feature now made it into C# by using optional parameters. The attributes CallerFilePath, CallerLineNumber, and CallerMembername can be used with optional parameters. Thus it’s easy to change the line numbers like in C++ but without Macros.

Compiler as a Service – Codename Roslyn

Looking more into the future of C#, Anders introduced the current state of compiler as a service. Scenarios that are possible with this are meta-programming, read-eval-print loops, DSL embedding, accessing the complete language object model…

Anders showed how to copy C# code and paste it as Visual Basic, and the other way around. Refactoring a data class by implementing INotifyPropertyChanged to extend the properties automatically. A C# interactive Window where code can be added on the fly including intellisense and refactoring features.

I think this to be a big changer in the features available within Visual Studio and expect a lot of extensions not only from Microsoft but also coming from the community.

A CTP will be available In four weeks from now.

Summary

To summarize the most important parts: C# deeply supports the Windows Runtime, makes async programming really easy, hybrid C#/JavaScript applications are easy to do, and a CTP for Roslyn will be available soon.

Christian

CN innovation

11/19/2010

Async Programming with .NET and C# v.next

As more and more cores are the norm with PC’s (I also expect to have smartphones with multi-core CPUs soon), programming with multiple threads gets more and more important.

This blog post gives an introduction to a new C# feature for working asynchronously by comparing it to older technologies.

.NET has some history on async programming:

  • With .NET 1.0 the async pattern was available to have a standard way to deal with long running methods.
  • .NET 2.0 added the async component pattern or async event pattern that made it easier with Windows-based programs. The async pattern from .NET 1.0 had the disadvantage that a callback method that is invoked when the long running operation completes makes use of a background thread and thus it is necessary to switch to the UI thread that owns the synchronization context.
  • With .NET 4 several enhancements have been done to write asynchronous methods. .NET 4 added a standard cancellation mechanism, the Task library and Parallel Lf deINQ.

C# so far only had the lock keyword to synchronize multiple threads. This changes with the next version of C# that offers async and await keywords.

Before showing the upcoming C# feature let’s compare this with older ways of programming asynchronously. The first sample shows downloading some data in a synchronous manner with the WebClient class. DownloadData can be used to get data from a server into an byte array.

private void OnSync(object sender, RoutedEventArgs e) { byte[] data = null; textStatus.Text = string.Empty; using (WebClient client = new WebClient()) { data = client.DownloadData(address); textStatus.Text = "Completed"; } }

Doing this from within a Windows application, the user interface is stalled while the synchronous method DownloadData waits until all the data is retrieved from the server.

To not block the UI, the data can be retrieved in an async manner. The second sample shows the use of the async pattern. This pattern defines a Begin and End prefix to the methods used for async calls and makes use of the IAsyncResult interface.

Contrary to the HttpWebRequest class, the WebClient class does not offer this pattern by itself. The HttpWebRequest class could be used to invoke the methods BeginGetResponse and EndGetResponse that follow the async pattern. To invoke any synchronous method in an async manner also a delegate can be used. This is shown in this sample.

For invoking the method WebClient.DownloadData a delegate that requires a string parameter and returns a byte array is defined with the Func<string, byte[]> delegtate. The delegate instance named download references a lambda expression that gets a string parameter and returns the result from the WebClient.DownloadData method. The implementation of the lambda expression is invoked asynchronously by calling the BeginInvoke method from the delegate instance. The first argument of this method defines the input data for the method that is invoked by the delegate. With this argument value the method that is referenced by the delegate is invoked from  thread pool thread.

The second parameter is of type AsyncCallback that is void and requires an IAsyncResult parameter. This parameter defines the method that is invoked as soon as the asynchronous method completes. Invoking the method EndInvoke from the delegate instance, the result (in this case a byte[]) is returned.

Invoking methods and properties from UI elements cannot be done directly, as the method that is assigned to the AsyncCallback is running within a background thread. To switch back to the UI thread, with WPF the Dispatcher property that returns a DispatcherObject can be used. The Invoke method of the DispatcherObject requires a delegate with the first parameter. Here, the Action<string> delegate is used to pass a string to the method.

private void OnAsync1(object sender, RoutedEventArgs e) { textStatus.Text = string.Empty; byte[] data = null; using (WebClient client = new WebClient()) { Func<string, byte[]> download = addr => { return client.DownloadData(addr); }; download.BeginInvoke(address, new AsyncCallback(ar => { data = download.EndInvoke(ar); Dispatcher.Invoke( new Action<string>(s => textStatus.Text = s), "Completed"); }), null); } }

Because of this complexity in special with Windows applications where it is necessary to get back to the UI thread the async event pattern was introduced with .NET 2.0. This pattern defines that a async method is postfixed with the name Async and defines an event with the postfix Completed that is invoked as soon as the async mehtod finishes. The big advantage in contrast to the callback method with the async pattern is that the event handler that is assigned to the Completed event is invoked from a thread that has the synchronization context. With WPF or Windows Forms applications this is the UI thread.

Doing the same sample as before with the async event pattern methods from the WebClient class can be used directly as this class offers an implementation of this pattern. The DownloadDataCompleted event a lambda expression is assigned to get the result from the async call, and change that status information in a TextBlock directly.

private void OnAsync2(object sender, RoutedEventArgs e) { textStatus.Text = string.Empty; using (WebClient client = new WebClient()) { client.DownloadDataCompleted += (sender1, e1) => { byte[] data = e1.Result; textStatus.Text = "completed"; }; client.DownloadDataAsync(new Uri(address)); } }

With WPF and Windows Forms the async event pattern is a lot easier to deal with contrary to the async pattern. However, it is still very different to programming synchronously. Before the async method is invoked it must be defined what happens when the method is finished which can make it quiet complex reading such code.

A goal of the new C# keywords is to write asynchronous code in a way that is similar to programming synchronous code. This sample requires the use of the Visual Studio Async CTP and a reference to the AsyncCTPLibrary assembly. This assembly contains an extension method to WebClient named DownloadDataTaskAsync that returns Task<byte[]>. Instead of using the task that is returned from this method the await keyword is used that means we’re waiting on the result of the task that is of type byte[]. Waiting here with the await keyword does not block the thread. Instead, the UI thread can do some other actions and gets informed by a message when the task is completed, so it can continue with the result that is returned from DownloadTaskAsync.

private async void OnAsync3(object sender, RoutedEventArgs e) { textStatus.Text = string.Empty; using (WebClient client = new WebClient()) { byte[] data = await client.DownloadDataTaskAsync(address); textStatus.Text = "Completed"; } }

Programming asynchronously this way is very similar to programming synchronously. The order of the code is similar to synchronous programming and it still behaves asynchronously.

async and await are just language features. It was possible to do the same with the current version of the compiler, the code just reads more complex.

This is really a great feature of the next version of the C# compiler. Expect more information about this in my blog.

Christian

CN innovation

Follow me on twitter

10/29/2010

PDC 2010 Day 1

Last year’s PDC was not about completely new things, but progress, updates to existing technologies. This continues with this year’s PDC. There’s great progress on existing technologies.

Some highlights?

Steve Ballmer’s keynote was on Internet Explorer 9 and Windows Phone 7.

Internet Explorer 9

IE9 has a big focus on standard HTML 5, HTML 5 features with hardware acceleration.

A differentiation of this browser in contrast to the competition is in the integration with Windows 7. Where WPF 4 got improvements for an integration with the Windows 7 taskbar, the same is now possible for Web sites by using IE9 features. This integration is really simple – using metatags to define the items of the jumplist, and a few lines of JavaScript to add custom functionality such as start/stop buttons to the preview.

IE 9 platform preview 6 is available at http://www.ietestdrive.com.

Windows Phone 7

Of course Windows Phone 7 had a big focus at PDC. The phone is different – I’m already using it for a week, it is really different. Metro gives a cool UI experience.

twitter and facebook applications were shown – with great UI features.

And really cool – at least for all attendees - a WP7 LG Optimus 7 was given to every attendee (with the exception of government attendees).

Visual Studio gets a profiler to analyze WP7 applications. This looked like a great way to analyze bottlenecks.

For programming, Charles Petzold’s Windows Phone 7 book is available for download.

Windows Azure

Keynote part 2, Bob Muglia’s focus was on Windows Azure. It was interesting to see that Pixar RenderMan is running on Windows Azure. This makes it possible for smaller studios to create animation by renting CPU power for a specified time. I’m seeing Azure not only important for scale up and scale down scenarios, but also to have access from everywhere, from every device.

Windows Azure gets a lot of improvements:

  • Virtual Machine Role
  • Application Virtualization – transfer application images
  • Extra small instance – of course for a lower price
  • Remote Desktop
  • Full IIS
  • Virtual Network
  • Elevated Privileges
  • Windows Server 2008 R2 Roles
  • Multiple Administrators
  • Marketplace – DataMarket (known as Dallas)

Was the Visual Studio Team Foundation Server too much admin work to consider? Now it’s in the cloud!

Windows Azure AppFabric has been updated with enhancements and new services:

  • Access Control
  • Caching
  • Service Bus
  • Composite Applications

SQLAzure with

  • Reporting
  • Data Sync

 

C# and Visual Basic next

The major focus on the next version of C# and Visual Basic is on asynchronous programming. Based on the Task<T> defined by .NET 4 the language keywords async and await have been added. These keywords make it possible to  that make it possible to write applications asynchronously in a synchronous programming style. This is really cool! I’ll blog some examples on how this can be used soon.

The Async CTP is available for download.

And More

With just two days PDC it’s not possible to have a session on every technology, which doesn’t mean there’s no progress. With PDC also some pre-recorded sessions are available, e.g. on WPF, and information on the future of WPF is here. Enhancements that can be expected with the next version:

  • Hosting of Silverlight content
  • Better AirSpace management with native HWND
  • Binding and change notification for collections from background threads
  • Better integration with UI virtualization
  • Integration of Ribbon
  • more…

Expect more of this content to be covered in my blog.

Christian

CN innovation

07/30/2010

Cancellation with .NET 4 (Part 2)

Part 1 of this series introduced the async patterns and introduced cancellation with the BackgroundWorker class as it existed since .NET 2. This part shows how the new .NET 4 cancellation framework can be used.

Previously to .NET 4, cancellation with async method calls was implemented in different ways if it was supported at all. For example, the BackgroundWorker implements cooperative cancellation by invoking the CancelAsync method, the long-running method needs to verify if it should be canceled by checking the CancellationPending property and needs to cancel by setting the Cancel property of the DoWorkEventArgs. More about this in the previous blog entry.

.NET 4 now supports cooperative cancellation of async methods in a standard way. The heart of this new framework is the CancellationToken struct. The CancellationToken is created by a CancellationTokenSource. This token can then be passed to any activity that should be cancelled. In case of a cancellation, the async call can verify cancellation by checking the IsCancellationRequested property of the CancellationToken. This unified model is now available with several classes offering asynchronous requests.

Cancellation of a Parallel Loop

The first example demonstrates cancelling a parallel for loop. Parallel.For is new with .NET 4 for doing iterations in parallel. In the sample the loop is cancelled from a separate task after 500 ms.

First a CancellationTokenSource is created. The separate task to cancel the loop invokes the Cancel method of the CancellationTokenSource to cancel the task(s) that have the cancellation token associated.

The Parallel.For method does a parallel loop from 0 to 100 and invokes the method that is defined by the fourth parameter that is of type Action<int>. The parameter that is received with the Action<int> delegate is the index of the loop. The implementation of this method just loops with a normal for and does a small sleep. At the begin and the end of the implementation a start and finish message is written so it can be seen if the iteration was completed.

With the third parameter ParallelOptions are passed where the CancellationToken property is assigned to the CancellationToken from the CancellationTokenSource. This makes it possible to cancel the loop.

In case of a cancellation, an exception of type OperationCanceledException is thrown.

           var cts = new CancellationTokenSource();

            // start a task that sends a cancel after 500 ms       
            new Task(() =>
               {
                   Thread.Sleep(500);
                   cts.Cancel(false);
               }).Start();

            try
            {
                ParallelLoopResult result =
                   Parallel.For(0, 100,
                       new ParallelOptions
                       {
                           CancellationToken = cts.Token
                       },
                       x =>
                       {
                           Console.WriteLine("loop {0} started", x);
                           int sum = 0;
                           for (int i = 0; i < 100; i++)
                           {
                               Thread.Sleep(2);
                               sum += i;
                           }
                           Console.WriteLine("loop {0} finished", x);
                       });
            }
            catch (OperationCanceledException ex)
            {
                Console.WriteLine(ex.Message);
            }

     

With the parallel for when a cancellation occurs all iterations hat have been started can continue to the end. However, new operations are not started anymore. This can easily be verified by checking the output as shown here.

loop 0 started
loop 50 started
loop 50 finished
loop 51 started
loop 0 finished
loop 1 started
loop 1 finished
loop 2 started
loop 51 finished
loop 52 started
loop 2 finished
loop 52 finished
The operation was canceled.

Cancellation of a Task

The parallel loop can do the cooperative cancellation on its own. This is not possible with an asynchronous running task as there’s no way to know when the task can be cancelled without knowing the method that is called. The implementation of the task method needs to cancel itself in case a cancellation is requested.

Similar as in the previous sample again a CancellationTokenSource is created. The CancellationToken that is associated with the CancellationTokenSource is passed on creation of the TaskFactory. Alternatively a CancellationToken can also be passed on creating a new task. The task that is created from the TaskFactory has an implementation that verifies if cancel should be done by checking the IsCancellationRequested property from the CancellationToken. In case cancel should be done an exception of type TaskCanceledException is thrown with the help of the method ThrowIfCancellationRequested. The type TaskCanceledException derives from the base class OperationCanceledException. The exception can be caught by someone waiting on the task.

            var cts = new CancellationTokenSource();

            // start a task that sends a cancel after 500 ms 
            new Task(() =>
            {
                Thread.Sleep(500);
                cts.Cancel();
            }).Start();

            var factory = new TaskFactory(cts.Token);
            Task t1 = factory.StartNew(new Action<object>(f =>
                {
                    Console.WriteLine("in task");
                    for (int i = 0; i < 20; i++)
                    {
                        Thread.Sleep(100);
                        CancellationToken ct = (f as TaskFactory).CancellationToken;
                        if (ct.IsCancellationRequested)
                        {
                            Console.WriteLine("cancelling was requested");
                            ct.ThrowIfCancellationRequested();
                            break;
                        }
                        Console.WriteLine("in loop {0}", i);
                    }
                    Console.WriteLine("task finished");
                }), factory);

            try
            {
                t1.Wait();
            }
            catch (AggregateException ex)
            {
                foreach (var innerEx in ex.InnerExceptions)
                {
                    Console.WriteLine(innerEx.Message);
                }
            }

It’s always the same. No matter what asynchronous operations are available, they should be cancelable with the help of a CancellationToken. That’s one of the great new features of .NET 4.

More about asynchronous programming with .NET 4 in my book Professional C# 4 with .NET 4 and in my .NET 4 workshop.

Christian

07/28/2010

Cancellation with .NET 4 (Part 1)

For calling methods asynchronously, since .NET 1.0 the async pattern can be used. .NET 2.0 added the event-based async pattern (also known as async component pattern) that makes async calls easier with Windows applications. Before .NET 4 no standard mechanism has been available to cancel asynchronous method calls. That’s new with .NET 4.0.

In this blog series you can read about these async patterns as well as the new unified model for cancellation.

Async Pattern

Calling methods asynchronously several classes from the .NET framework implement the async pattern. This pattern is available with file I/O, stream I/O, socket I/O, WCF proxies, Message queuing… and delegates.

If there’s a synchronous Foo method, the async pattern defines the BeginFoo and EndFoo methods. The BeginFoo method returns IAsyncResult that can be used to check the async method if it is completed, and allows waiting for it by using a WaitHandle. Passing a AsyncCallback delegate allows defining a handler method that gets invoked when the async call is finished. The issue here is that the handler method is invoked from a pooled thread and thus if the handler should do some changes on Windows elements a thread switch must be done to the thread owning the Window handles.

Event-based Async Pattern

The async component pattern made async calls with Windows applications easier because the switch to the Window thread is already done.

If there’s a synchronous Foo method, the async component pattern defines the method FooAsync that receives the input paramters of Foo. A event named FooCompleted is invoked when the async method is finished. The advantage of the event model here is that the handler is invoked from a thread that holds the synchronization context. With WPF and Windows Forms application the UI thread is assigned the synchronization context with WindowsFormsSynchronizationContext or DispatcherSynchronizationContext.

The event-based async pattern is implemented by several .NET classes, e.g. the BackgroundWorker, WebClient and WCF proxies.

Cancellation

Async calls can take a while before the result is returned. Thus it can be useful to cancel the call. Before .NET 4 there was no uniform way to support cancellation.

Of course cancellation is available with async classes before .NET 4. For example, the BackgroundWorker supports cancellation as shown in the following code sample.

To enable cancellation with the BackgroundWorker the property WorkerSupportsCancellation must be set to true.

        private BackgroundWorker worker;

        public MainWindow()
        {
            InitializeComponent();
            worker = new BackgroundWorker();
            worker.WorkerSupportsCancellation = true;
        }

The BackgroundWorker implements the async event pattern by defining the method RunWorkerAsync and the event RunWorkerCompleted. RunWorkerAsync starts the asynchronous call that is defined by the DoWork event. RunWorkerAsync requires  single argument of type object. The sample code passes two values from textboxes by creating a tuple.

The DoWork event of the BackgroundWorker defines the method that is invoked when the async request is started. The implementation simulates a long-running method by using a for-loop and Thread.Sleep. Within the loop it is verified if the call should be canceled by checking the CancellationPending property from the BckgroundWorker. If this is the case, the method returns after setting the Cancel property of the DoWorkEventArgs type to mark cancelation.

The RunWorkerCompleted event is fired as soon as the async method is finished, no matter if it was running successful or is canceled. In case of a cancelation an event of type InvalidOperationException is fired with the information “Operation has been cancelled”.

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            worker.DoWork += (sender1, e1) =>
                {
                    var input = (e1.Argument as Tuple<int, int>);

                    for (int i = 0; i < 10; i++)
                    {
                        Thread.Sleep(1000);
                        if ((sender1 as BackgroundWorker).CancellationPending)
                        {
                            e1.Cancel = true;
                            return;
                        }
                    }

                    e1.Result = input.Item1 + input.Item2;
                };
            worker.RunWorkerCompleted += (sender1, e1) =>
                {
                    try
                    {
                        textBox3.Text = e1.Result.ToString();
                    }
                    catch (InvalidOperationException ex)
                    {
                        textBox3.Text = ex.Message;
                    }
                };
            worker.RunWorkerAsync(Tuple.Create(int.Parse(textBox1.Text), int.Parse(textBox2.Text)));
        }

The BackgroundWorker is canceled by invoking the method CancelAsync.

           worker.CancelAsync();

In summary, the BackgroundWorker implements cooperative cancellation by invoking the CancelAsync method, the long-running method needs to verify if it should be canceled by checking the CancellationPending property and needs to cancel by setting the Cancel property of the DoWorkEventArgs.

 

My next blog entry demonstrates how cancellation can be done with .NET 4.

 

More about asynchronous programming with .NET 4 in my book Professional C# 4 with .NET 4 and in my .NET 4 workshop.

 

Christian

04/05/2010

Enumerating Files and Directories with .NET 4.0

With .NET 4 the Directory and DirectoryInfo classes have been extended to allow for enumerated access to filenames and directories. EnumerateFiles, EnumerateDirectories, and EnumerateFileSystemEntries are the new methods to enumerate files, directories, and both files and directories. Instead of retrieving all file system entries before they can be used, with the new methods an enumerator is offered to access the file system and retrieve the filenames during the loop of a foreach statement. This is cool for not having to wait until all the filenames are retrieved. The older methods GetFiles, GetDirectories, and GetFileSystemEntries returned a string[] and thus the result could only be used as soon as the method was finished.

The new methods have three overloads to specify a search pattern and search options beside the path where the search starts. With the SearchOption enumeration it can be specified if only the top directory (TopDirectoryOnly) should be accessed, or the complete directory tree (AllDirectories).

var files = Directory.EnumerateFiles(@"\\server\share", "*", SearchOption.AllDirectories).Take(10);
foreach (var file in files)
{
Console.WriteLine(file);
}

As IEnumerable<string> is returned from these methods, they can also be used with all the LINQ methods and in a LINQ query.

There’s one important restriction with the new methods. The new API cannot be used to search through the complete disk because with directories that cannot be accessed an exception of type UnauthorizedAccessException is thrown and the enumeration stops. The reason for this is that the methods are designed similar to the existing methods that returned a string array. In a future version a search option such as ContinueOnError might be added as described on the Microsoft Connect site. If this is a feature you want, please vote at the Connect site.

More information on .NET 4 in my new book Professional C# 4 with .NET 4 and in my Take off to .NET 4 workshop.

Christian

10/31/2008

PDC 2008 - XAML with .NET 4.0

from #pdc2008: XAML enhancements!
XAML nowadays is used with the UI (WPF, Silverlight), Workflows (WF), and Electronic Paper (XPS).
XPS is just going to be an ECMA standard!

With all these uses XAML is going into a language evolution. Goals of this is to make XAML faster and easier to use.

The XAML language extensions are defined by this list:

  • improved named references
  • support for built-in types
  • full generics support
  • support for arbitrary dictionary values
  • declarative events without compiling
  • declarative definition of types
  • arguments for non-default constructors
  • factory methods
The notepad for XAML, XAMLPad, has been enhanced. Besides the XML and object box it now gives a DOM box to display the DOM model. With the F12 key, a visual representation of the XAML type is shown.

For reading/writing/processing XAML, .NET 4.0 includes the System.Xaml.dll assembly. It contains XamlXmlReader, XamlXmlWriter, BamlReader, BamlWriter, DomReader, DomWriter, ObjectReader, ObjectWriter. Now it's easier to develop e.g. a SVG conversion. To convert from SVG to XAML, the SVGReader and XamlXmlWriter come into play. For creating objects on the fly out of SVG, SVGReader and ObjectWriter are used.
The System.Xaml assembly will be available here: http://go.microsoft.com/fwlink/?LinkId=132499

In the early days of XAML and WPF, simple applications have been shown that just need XAML code but no code-behind. Now it is possible to write an application that makes use of WPF, WF, and WCF purely using XAML.

Christian

10/29/2008

PDC 2008 - Parallel Extensions to the .NET Framework

From #pdc2008, Parallel extensions to the .NET Framework are part of .NET 4.0!

The thread pool has been enhanced with great new features. The new features can be accessed from the Task API. The Task API can be used similar to the Thread class and offers some advanced features. For the tasks to queue up, the pool now not only includes a global queue but also a local queue for every thread in the pool. This can enhance performance because of data cached in the CPU.
With the new API, other than starting tasks some more features: tasks can be started in a parent/child relationship, it is possible to suspend/continue/wait/cancel tasks, and get results from the task (using the Future class). This class might be renamed to Task as well (in the future).

Tasks are well integrated into Visual Studio 2010. For debugging tasks new windows Parallel Tasks and Parallel Stacks are available.

A common pattern is using threads in a loop to perform some actions on a list of items. The Parallel class gives an implementation of this pattern. Parallel.ForEach offers several overloads to do several actions in parallel with the thread pool.

Declarative data parallelism allows LINQ queries to run in parallel. This feature is for LINQ to objects thus collections that implement IEnumerable. All that needs to be done is to invoke the AsParallel method that does nothing more than casting the IEnumerale interface to IParallelEnumerable. The class ParallelEnumerable then offers extension methods for the IParallelEnumerable interface to call the LINQ operators using threads from the pool.

Christian