Selecting a Windows Mobile API - .NET Compact Framework and Win32

4/7/2010

Paul Yao, The Paul Yao Company

April 2009

This article discusses the Microsoft® Win32® API and the Microsoft .NET Compact Framework (NETCF) APIs for use on Windows Mobile® 6 and later. After a brief introduction of Web-based technologies, this technical article focuses on selecting an API for creating thick-client applications.

Windows Mobile 6 and later

Microsoft .NET Compact Framework 3.5

Microsoft Win32 API

Some choices in life carry more consequences than other choices. This means that the effect is felt long after the choice is made. For software development projects, one consequential choice is selecting the APIs for targeting a new platform. Usually, choices involve studying the trade-offs among alternatives. To select the correct APIs, you must understand the alternatives and the relative benefits of each alternative. This article compares the key differences between the available choices for developing Windows Mobile devices.

Carefully weigh the alternatives for selecting an API. Making the correct choice is important because of the work involved in designing, writing, debugging, and deploying software. After you have made a choice, it becomes more and more difficult to undo that choice and use an alternative. After you have made an investment in one API, there is little chance that you will reverse your decision and port your code to another API. Each day of writing code for one API is an investment into that API, and so a change in the middle of a project doubles your development costs. So choose carefully, choose wisely, and choose wisely early, and enjoy the benefits of that choice.

Before weighing the intrinsic merits of available APIs, take a moment to consider three external factors which might affect your choice:

  • Existing source code
  • Your team’s skill set
  • Vendor support for the API and supporting tools

What existing source code do you own? This is an important factor because existing source code can potentially shorten your development task. Especially if the existing source code has gone through a complete development-test-deployment cycle, such software likely is of better quality than any new code that you might write. In an ideal world, you would spend a morning porting code from an older platform and spend the afternoon celebrating. Of course, such ideal scenarios rarely become a reality. Existing code may have to be restructured to separate the "basic" code (key algorithms, proprietary functions, unique data tables, and more) from the "accidental" portions which typically need rewriting (user interface, test code, scaffolding code, and more) The good news here is that making any existing code more portable today can pay dividends on future porting efforts.

What skills does your development team have? Your development schedule is obviously affected if the skills that your project requires differ from the ones that your team members actually have. A team where most of the members are new to a specific API (or platform) requires more time than a more experienced team. Consider the time that a team requires for learning and obtaining outside training. Having a team with strong skills in one API versus another API might influence your choice of APIs. Alternatively, you might have to choose the API before your team is fully assembled. If that is the case, experience with the target API might become part of the hiring criteria.

What vendor support can you expect? The most important factor for selecting an API involves the vendor’s expected investment in an API and supporting tools. Microsoft has historically targeted the software developer, both its own employees and the employees of its customers, as strategic stakeholders. Therefore, the company has made significant investments in APIs and development tools, the best examples being the .NET Framework and Microsoft Visual Studio® 2008. When APIs or tools become outdated, Microsoft does not invest in outdated APIs, such as Embedded Visual Basic. However, third parties can step in and support such technologies.

Available Windows Mobile APIs

How many Windows Mobile APIs are there? Table 1 summarizes five Windows Mobile APIs, the four supported source-level programming languages, and the two kinds of machine languages. This list is somewhat arbitrary, because it omits older technologies such as Microsoft Embedded Visual Basic and also third-party languages such as Borland Delphi. However, for the purposes of this article, it does represent most of the existing sample code that you are likely to encounter on the Web or bundled into a Windows Mobile SDK.

The set of APIs and source languages suggests that a hiring manager has to look beyond the question of someone having "Windows Mobile programming experience" and ask detailed questions about experience with specific APIs. For the development leads who find that they have inherited "some Windows Mobile code", you must dig deeper to determine the specific flavor you are receiving. Generally, it is difficult to blend, for example, Win32 code and Microsoft Foundation Class (MFC) code. At the same time, every Windows Mobile programmer needs some knowledge of these different flavors, to make sense of the available sample code that was included with the SDKs and posted in various locations on the Web.

Table 1 Windows Mobile APIs

API Source language Machine language

.NET Compact Framework (CF)

Visual C#®, Visual Basic® .NET

Intermediate Language (MSIL)

Windows 32-Bit Interface (Win32)

C, Visual C++®

Native ARM v4i

Microsoft Foundation Class (MFC)

Visual C++

Native ARM v4i

ActiveX® Template Library (ATL)

Visual C++

Native ARM v4i

Windows Template Library (WTL) *

Visual C++

Native ARM v4i

All APIs listed in Table 1 are supported by compiled languages. The executable file format corresponds to that of "PE" (portable executable) files, such as that found on developer workstations running Windows®. One differentiating factor is that the NETCF programs are compiled into the portable MSIL machine language. MSIL is a portable machine language format that can run on any system with the needed just-in-time (JIT) compiler, a standard part of the .NET runtime. Whereas NETCF programs might have been written for a Windows Mobile device, the presence of MSIL means that NETCF programs can run on developer workstations running Windows when the .NET Framework (version 1.1 and later) was installed. This support does have its limits, based on references to Windows Mobile-specific assemblies and the use of P/Invoke to call Windows Mobile-specific DLLs. These limitations aside, the binary compatibility between Windows Mobile and developer workstations running Windows provided by NETCF is truly remarkable. Theoretically, a clever software team could develop a library and deploy it across many different platforms that span devices, developer workstations, and servers.

As shown in the table, four of the APIs create native ARM v4i executable files. At the source level, these four APIs look very different from one another. However, in their machine language form, they are nothing more than variations of the native Win32 API. For this article, I am ignoring the source-level differences and focus instead on differences between managed and native APIs. This is appropriate, because three APIs, MFC, ATL, and WTL, are surrogates for Win32 and serve primarily to repackage the core Win32 API.

This article focuses on comparing the Win32 API and the NETCF API for thick-client Windows Mobile applications. This is not to suggest that Web-enabled applications are not important, and indeed there is a lot going on involving Web browsers, Rich Internet Applications (RIAs) platforms like Silverlight® and Windows Azure Cloud. This article targets those who are building a thick-client application, and want some guidance in choosing between two available choices: Win32 and the .NET Compact Framework.

Development Tools

A single development tool, Microsoft Visual Studio 2008, supports developing for both native (Win32) applications and managed (.NET Compact Framework) code. This is the same tool that developers use to develop ASP.NET Web sites and Windows Presentation Foundation (WPF) thick-client applications for Windows Vista. You benefit from a tool in which Microsoft has invested many development resources improving and fine-tuning over the years. However, be aware that the free version, Visual Studio Express, does not support Windows Mobile development. Instead, Visual Studio Standard is the minimum version that is required.

Visual Studio 2008 is an "Integrated Development Environment" (IDE), because it brings together various separate tools. Among included tools are language compilers and object linker, Text Editor, wizards to simplify automatic code generation, and a source-level debugger. Developing for Windows Mobile requires a Software Development Kit (SDK) for each targeted device. For example, Visual Studio 2008 is included with three Windows Mobile SDKs: one for Pocket PC 2003, another for Windows Mobile 5.0 Pocket PC SDK and a third for Windows Mobile 5.0 Smartphone SDK. You can download the SDKs for other platforms, such as for Windows Mobile 6 Standard and Professional devices.

Among its other tools, Visual Studio 2008 also provides a Windows Mobile device emulator. This software enables you to run Windows Mobile executables on a developer workstation Windows system without having to have a Windows Mobile device. The emulator is binary compatible with an actual Windows Mobile device that means you can run executables files which contain the ARM instruction set. Of course, no amount of emulator testing replaces the testing on actual Windows Mobile hardware. What the device emulator does provide is another choice to help supplement the on-device testing that you do.

The most important benefit of managed code is programmer productivity. All other things being equal, the output of any process is limited by the scarcest resources. In software development, that resource is time, specifically developer time. Some people consider the .NET garbage collector as an important part of the improved productivity story, and correctly so. However, what is even more significant is the API organization. The organization of the large API into classes and namespaces helped create a level of discoverability that did not exist in the Win32 API.

Microsoft introduced its first version of the .NET Framework in July 2000 at a Professional Developers Conference held in Orlando, Florida. This was not the first time that the company had introduced a new technology to improve programmer productivity. At that time, for example, Microsoft Visual Basic® was at least ten years old. What made the introduction of .NET significant was the breadth and depth of what it provided. In one stroke, the company was providing a whole new set of tools and a new API for use in creating client and Web-based applications.

Benefits of Managed Code

The .NET Compact Framework provides a subset of the .NET Framework. At the same time, the Compact Framework inherited the structure and organization of the .NET Framework. This meant that a programmer familiar with the System.Windows.Forms namespace on the full framework would find many similarities in the Compact Framework. Of course, the Compact version did not have all the classes, properties, methods, or events, but the syntax for the elements which are present is identical.

Programmer productivity is improved in many ways. One way is the organization of namespaces so that you can easily discover all related classes. For example, after you know that user interface classes are located in the System.Windows.Forms namespace, it is easy to look in that one location to find most every type that you want. Programming interfaces are growing larger and more complex so that anything that helps programmers find what they are looking for automatically makes them more productive.

The world of .NET programming for both the .NET Framework and the .NET Compact Framework is a world of object-oriented programming (OOP). There are several benefits that are derived from this. One is support for encapsulation that means the designer of a class may choose to hide some elements away from the user of a class. This improves code robustness by keeping those things hidden which may change in future versions or which, for various reasons, must remain undocumented.

Another OOP feature is inheritance. Inheritance enables new code to be written that builds on existing code. Inheritance is used within the .NET Compact Framework itself, where many of the built-in classes are built through a long chain of inheritance. For example, the TextBox class has five base classes and two other classes which themselves inherit from TextBox. As provided in the MSDN documentation, here is the inheritance hierarchy for the TextBox class:

System..::.Object

System..::.MarshalByRefObject

System.ComponentModel..::.Component

System.Windows.Forms..::.Control

System.Windows.Forms..::.TextBoxBase

System.Windows.Forms..::.TextBox

System.Windows.Forms..::.DataGridTextBox

System.Windows.Forms..::.DataGridViewTextBoxEditingControl

Another important OOP feature is support for strong types. This feature increases code robustness by providing a set of rules for when and how one type can be converted into another type. This is unlike traditional C programming, where you can coerce one type to be another type. As convenient as casting may be, it also enabled for various kinds of type conversion errors to remain hidden. It is much more difficult to hide such problems in a .NET program, because you cannot even compile code which contains type errors.

And then there is the support that is provided by the garbage collector in the form of memory cleanup. Microsoft .NET garbage collector is not the first garbage collector ever created. Earlier examples of systems with garbage collection include SmallTalk, Visual Basic, and Java by Sun. To a programmer, the primary benefit of garbage collection is that you can "allocate and forget" and be fairly confident that the runtime system will find and reclaim memory when it is not needed.

The presence of garbage collection provides an important helper for programmers. But it does not completely take away from the need of programmers to be as efficient as possible. As an obvious example, you should avoid allocating many small (less than eight byte) objects because the overhead for each object is at least four bytes, and many 8-byte objects would therefore incur a built-in cost of 50 percent for each object allocated. Finding some way to combine small objects would make memory use more efficient (for example, putting the previously mentioned small objects into one or more arrays).

The garbage collector also cannot help when you are allocating native objects from managed code. For example, if you allocate native memory and pass that memory to a native Win32 function, the garbage collector cannot help you. Instead, you must follow whatever cleanup rules apply to that specific Win32 function.

To help with such situations, the architects of .NET did provide the Dispose and the Finalize methods to enable cleanup under special circumstances. In other words, the garbage collector itself provides no help for cleaning up native objects. But a managed object that contains one or more native object can take advantage of special features to perform the required cleanup of the nested Win32 objects.

.NET Compact Framework Features

Undoubtedly the productivity aspects of .NET are appealing. But the general design of an API does not guarantee its suitability for specific applications. For that, you must examine the API and the specific features that it supports. Generally, the ideal Compact Framework application has a forms-based user interface, works with many record-oriented data, and communicates with client or server systems over a network.

This broad description is not meant to define the ideal application, but one that takes advantages of some significant features of the API. What about other applications that do not exactly match this general description? For those, you can match your feature needs to the general feature set for what is supported in the Compact Framework. Tables 2-4 provide a summary of the features that are built into .NET Compact Framework 3.5. These tables were created by using namespace and class information that are available through the Object Browser feature of Visual Studio 2008.

Table 2 summarizes what might be called "core .NET support". The classes in these namespaces provide the foundation for building applications. The base types on the desktop are the same as the base types found on devices. Devices have a hierarchical file system and a hierarchical registry, exactly like on the desktop. Whereas device storage may be more limited than on the desktop, the .NET classes that access them are identical.

As expected in a graphical user-interface, you have built-in user interface objects that support rich text in the form of TrueType® fonts. Both device and desktop APIs enable rich graphical output, in the form of both vector and raster graphics. Devices are limited to being able to draw 2-dimensional, nonrotated graphics, whereas desktop systems support 3-dimensional graphics, with rich support for rotation.

Table 2 – Core .NET Support

Namespace Comments

System

Base types

System.IO

File I/O

Microsoft.Win32

System registry

Microsoft.VisualBasic

Support for Visual Basic 6 compatibility helpers

System.Globalization

Localization classes

System.Collections

Collection support includes ArrayList, Hashtable, Queue, SortedList, and Stack

System.Drawing

Two-dimensional graphical output

System.Reflection

Ability to read and parse managed assemblies (but no support for generating code – Emit)

System.Runtime.InteropServices

Calling functions in Win32 DLLs and also COM interoperability

System.Text

Convert strings between character sets

System.Threading

Multithreaded programming

System.Security.Cryptography

Encryption

System.Text.RegularExpressions

Text parsing

System.Windows.Forms

Form-based user interface

Table 3 summarizes the communications support that is built into .NET Compact Framework namespaces. One late-comer to both desktop and device-side programming is support for serial communications (for example, "COM1:" "COM2:" ports). The first versions of the .NET Framework on both desktop and device omitted this support. However, they have managed to find their way into later frameworks.

As for the rest of the communications support, most support is network-enabled communications technologies. Whether you want to build your own protocols in addition to the low-level sockets, or take advantage of the built-in support for higher-level protocols, both kinds of support are available. At the high end of the network protocol stack is support for building Web Service clients, and support for using the latest Windows Communication Foundation (WCF) protocol.

Table 3 – Communication Support

Namespace Comments

System.Net.Irda

Support for infrared communications

System.Messaging

Microsoft Message Queue (Message Queuing) support

System.ServiceModel

Windows Communication Foundation (WCF) support

System.Web.Services

Web service client support

Microsoft.ServiceModel.Channel.Mail

WCF service that uses e-mail as channel transport

System.IO.Ports

Serial communication

System.Net, System.Net.Sockets

Network programming

Table 4 summarizes the namespaces with data management support. For programmers who prefer to have data that is stored in rows and columns, there is ADO.NET. This API makes it easy to transfer data between memory and a relational database, such as Microsoft SQL Server® Mobile Edition. ADO.NET also enables transfer of data to XML, for those situations when you are looking for a non-proprietary format for exchanging data with other systems. Or if you prefer, there are several managed code solutions for working with raw XML itself.

Table 4 – Data Management Support

Namespace Comments

System.Data

ADO.NET - relational data sets in RAM.

System.Linq

Language integrated query (LINQ) support for manipulating 1-and 2-dimensional data arrays. This includes query, filtering, and arithmetic operations.

System.Xml.Linq

LINQ support for XML.

System.Xml.Serialization

XML serialization.

System.Xml.Schema

XML schema.

System.Runtime.Serialization

XML serialization.

System.Xml

XML manipulation.

Table 5 summarizes Windows-Mobile-specific classes which are found in the .NET Compact Framework. As suggested by these classes, Microsoft is more than willing to extend its managed code library to support application programming. At the same time, be aware that the use of these classes prevents an assembly from being able to run on the desktop. If portability between device and desktop is important to you, you just have to structure your code to take these device-dependent classes into account. One solution might involve putting all such dependencies into one DLL, and then replacing that DLL when it runs on the desktop.

Table 5 – Windows Mobile-Specific .NET Support

Namespace Class Comment

Microsoft.WindowsCE.Forms

DocumentList

Wrapper for Pocket PC document list control.

Microsoft.WindowsCE.Forms

HardwareButton

HardwareKeys

Support for Pocket PC hardware buttons.

Microsoft.WindowsCE.Forms

InputPanel

Controls on-screen keyboard (Software input panel) on Pocket PC and Windows CE.

Microsoft.WindowsCE.Forms

InputMode

Controls input mode on Smartphone keypads.

Microsoft.WindowsCE.Forms

LogFont

Full access to underlying GDI font capabilities.

Microsoft.WindowsCE.Forms

MessageWindow

Wrappers for Win32 window in managed code.

Microsoft.WindowsCE.Forms

Notification

Support for notifications.

Microsoft.WindowsCE.Forms

ScreenOrientation

Screen rotation support.

Microsoft.WindowsCE.Forms

SystemSettings

Pocket PC-specific settings.

Microsoft.WindowsMobile.DirectX

Microsoft.WindowsMobile.Direct3D

GraphicsStream

Windows Mobile support for DirectX 3-D graphical display.

Microsoft.WindowsMobile.Configuration

ConfigurationManager

Windows Mobile support for configuration manager. In the full framework, this is deployed in the System.Configuration namespace.

Microsoft.WindowsMobile.PocketOutlook

Appointment

Contact

EmailMessage

SmsMessage

Task

Enables access to Outlook Mobile data. This includes appointments, contacts, e-mail, SMS messages, tasks.

Microsoft.WindowsMobile.Forms

CameraCaptureDialog

ChooseContactDialog

SelectPictureDialog

Provides dialog boxes for camera support, picture viewing, and contact selection.

Microsoft.WindowsMobile.Status

RegistryState

SystemState

Managed wrappers for the State and Notification Broker.

Microsoft.WindowsMObile.Telephony

Phone

PHoneMakeCallInfo

Support for making phone calls.

When Microsoft Windows was introduced in the 1980s, the primary goal was to improve end-user productivity by enabling creating highly interactive, graphical application programs. At the time, character-based systems, such as Microsoft MS-DOS, provided the dominant user-interface and graphical systems, such as Microsoft Windows were just emerging. With the focus on the end-user, Windows designers did not even consider programmer productivity to be important. Then Programmers were considered the smart people who did the heavy lifting to make computer power available to everyone else.

The first API for Microsoft Windows was Win16, the Windows 16-Bit Programming interface. Created several years before the first PC-compatible C++ compilers were created, Win16 has no object-oriented programming (OOP) support. That was incorporated later, when COM was introduced that arguably did little to improve programmer productivity. Win32, the core API for today’s current operating systems, including Windows Mobile and Windows Vista, was designed as a widened version of Win16. The core API in today’s operating systems, then, was formed from technologies which date back over 25 years.

Challenges of Native Code

Lacking OOP support, Win32 is a function-oriented API. Functions are implemented in a sea of functions that are defined in a broad set of include (*.h) files. When you study the available functions, some patterns emerge – for example, mixing uppercase and lowercase letters for function names – but generally the names are arcane and sometimes difficult to determine. MapViewOfFile, for example, is the function that you call to access shared memory. CreateFile is the function that you call to open a file (in addition to actually creating a file, as suggested by the name). Into this non-OOP system, names that hint at OOP concepts have crept in, and include functions like RegisterClass and SelectObject. It is, in short, an arcane, cranky API.

Arcane function names are not the worst of Win32 problems. Of more concern is that the API is prone to memory leaks. The term "memory leak" refers to memory that is allocated but not cleaned up correctly. Memory leaks create problems on all systems, but such problems are emphasized on Windows Mobile devices with their small amount of RAM (compared to desktop systems) and the standard practice of having problems continually running for weeks and months. Under these constraints, memory leaks may cause devices to lock up. The only "solution," other than fixing or removing the offending code, is frequent restarts.

Applications that create certain operating system objects must make sure to also delete these objects or risk leaking memory. Whereas most objects are cleaned up when a process stops, this still creates a problem for processes which must run continuously. Such processes must be carefully crafted and tested to make sure that they are free from memory leaks. Table 6 summarizes the Win32 objects that require application cleanup.

Table 6 – Operating System Objects Which Require Cleanup

User Interface Objects

Accelerators, carets, classes, dialog boxes, icons, menus, mouse cursors, timer, windows

Graphical Objects

Bitmaps, brushes, device contexts (DCs), fonts, palettes, pens, regions

Kernel Objects

Atoms, important section, dynamic link library (DLL), file, file mapping objects, mutexes, processes, registry keys, semaphores, threads

Network Objects

Sockets, //http connections

Generally, developers who write managed code do not have to worry about leaking Win32 objects. Microsoft managed libraries do allocate Win32 objects. But the "managed wrappers" are built to make sure that the underlying Win32 objects are cleaned up correctly.

There is an important exception. That exception occurs when managed code that an application provides makes Win32 function calls that allocate a Win32 object. Managed code calls through to Win32 code by using the Platform Invoke (P/Invoke) mechanism. There is little chance that you will accidentally make a P/Invoke call, because the declarations include (among other things) the file name of the DLL that contains the desired function.

The Win32 API is required in three general cases: (1) for operating system (or "shell") extensions, (2) for Windows Mobile device drivers, and (3) for real-time threads. These three cases are described in the following sections.

Operating System Extensions

A key strength of Windows Mobile is its extensibility. For example, you can add items to the Today screen on a Pocket PC (or the Home Screen on a Smartphone). This capability enables applications to tie themselves to the unique capabilities of a device and interact with the user in ways that the user is familiar with. For all such extensions, your application must provide a dynamic link library (DLL) to the system, and such DLLs must be Win32 DLLs.

Table 7 summarizes the various Windows Mobile operating systems extensions. Generally, installation requires one or more entries in the system registry. Among other things, the registry entries identify the location and file name of the target DLL. Such DLLs must export one or more functions, the names of which sometimes appear in the registry and sometimes are determined by the kind of extension that you are creating.

Table 7 – Windows Mobile Operating System Extensions

Extension Description

Application Setup

Enables customization of program installation and un-installation.

Control Panel item

Control Panel item application, ctlpnl.exe, looks for DLLs with a .CPL extension. Those DLLs which export a CPLApplet entry point are treated as control panel programs.

File Filters

These in-process COM servers are Win32 DLLS that reside on developer workstations and convert files as they are transferred to Windows Mobile systems. On Windows XP and earlier, these DLLs run under ActiveSync. With Windows Vista and later versions, these DLLs run under the Windows Mobile Device Center (WMDC).

Home Screen Plug-In

On Windows Mobile Standard, provide a DLL with entry points for a COM in-process server (DllGetClassObject, DllCanUnloadNow, and more) to enable customizations of a mobile phone Home screen.

Internet Explorer Mobile Customizations

The Windows Mobile built-in browser can be customized in various ways, all which involve providing an in-process COM server DLL. Among the kinds of customizations are ActiveX controls and Browser Helper Objects

Software Input Panel (SIP)

Enable you to create a custom SIP on-screen keyboard entry panel by deploying a DLL with the required entry points.

Mobile File Explorer Extensions

The Windows Mobile Explorer enables extensions for context menus, property sheets, and drag-and-drop. For more information, see the include files aygshell.h and shlobj.h in the Windows Mobile SDK.

Today Screen Plug-In

On a Pocket PC (Windows Mobile Professional), provide a DLL with an exported entry point named InitializeCustomItem.

User Interface Skin

Customize the appearance of a Windows Embedded CE device with a set of DLLs that fine-tune the appearance of the system user-interface.

Device Drivers and System Services

All Windows Mobile device drivers and system services libraries are Win32 dynamic link libraries. Generally, device drivers run in the address space of a process named Device.exe. System service libraries run in the address space of a process named Services.exe. The difference between the two is somewhat arbitrary, as the two kinds of DLLs used to run in the same process address space in an older version of Windows Mobile. Tables 8 and 9 summarize some device drivers and system services which were found on a Windows Mobile Professional Device.

Table 8 – Examples of Device Drivers Found on a Windows Mobile Device

Driver Name Description

Battdrvr.dll

Battery driver

Backlight.dll

Controls LCD screen backlight level

Bta2dp.dll

Bluetooth audio driver

Ccoredrv.dll

SIM card driver

Flashdrv.dll

Flash memory storage driver

Msm7500usbfn.dll

USB function driver

Rilphone.dll

Radio interface layer driver

Softkb.dll

Software input panel (SIP), on-screen keyboard

WaveDev.dll

Speaker driver

Table 9 – Examples of System Service Libraries Found on a Windows Mobile Device

Service Name Description

Btagsvc.dll

Bluetooth audio gateway

BthASPlugIn.dll

Sync Bluetooth server

Credsvc.dll

Credential Manager

Enrollsvc.dll

Certificate enrollment engine

Lassd.dll

Local security authority service

Notify.dll

Notification service

ObexSrvr.dll

Object exchange service

PTTService.dll

Handles push-to-talk requests

Swmgmtservice.dll

Handles software component configuration

Real-Time Threads

In the world of mobile and embedded development, there is frequently a discussion about real-time requirements. A real-time requirement is one in which some task must be completed in a predefined time. The consequences of failing to meet the time limit might be inconvenient or it could lead to a failure. In the former case, this is also known as a "soft real-time requirement"; in the latter case, the term "hard real-time requirement" is frequently used.

An example of a soft real-time requirement is being able to receive and decode some streaming media, such as a song. A typical example of a situation with a hard real-time requirement is that of a robot arm which must retract before some heavy manufacturing component comes crashing down. In the first case, the user might hear a song warble. In the second case, some expensive piece of machinery might have to be replaced.

Generally, it is acknowledged that version 3.0 was the first version of Windows CE in which real-time support was needed by those with serious real-time requirements. For such developers, real-time work should be handled by a Win32 thread. The reason for this requirement relates to the way that the managed code garbage collector works. During the operation of the garbage collector, all managed code threads are frozen. At such moments, the system would be unable to enable a managed code thread to run. For the media download, this might be a workable situation. But with the robot arm that must be retracted, this limitation could cause the robot arm to be crushed.

There is an interesting design-pattern that you might consider following if you want to use managed code but also have the need for one or more real-time threads. You could build your application that uses the .NET Compact Framework, but implement all real-time code in a Win32 DLL. Using the P/Invoke support that is built into the NETCF libraries, you can call into the Win32 real-time DLL. An interesting thing happens when a managed thread calls into a Win32 DLL, because the garbage collector can detect the difference between when managed code is running and when native code is running. During garbage collection, native threads do not have to be frozen for garbage collection to work correctly. Such threads are only subject to the constraints of the operating system scheduler, and are not subject to the constraints of the garbage collector as long as they are executing native code. Garbage collection only causes native threads to stop running if control of the native thread passes back to the managed code callers, and then only until the garbage collection is finished.

You want to consider carefully what API to use because such a choice carries consequences. All other things being equal, Microsoft designed the .NET Compact Framework, just as its desktop counterpart, the .NET Framework, to improve programmer productivity. The world of managed development supports programmer productivity in several ways. One way consists of taking full advantage of object-oriented programming (OOP) features such as namespaces and classes. The garbage collector eliminates one tedious chore of Win32 programming, namely the need for the programmer to clean up objects when they are no longer needed.

Despite greater productivity, there are limits insofar as what you can achieve with managed code. Some situations require you to write Win32 code, such as when you extend the operating system, when you write device drivers and system services, and also when you write for real-time threads. In these cases, you have to make sure that your development team has some Win32 expertise. Outside this narrow band of requirements, .NET Compact Framework provides the APIs you want to use for your Windows Mobile development.

Author Bio

Paul Yao is co-author of the first book published on Windows programming and five other programmer-oriented books. Paul just finished an update to the second edition of his latest book, Programming the .NET Compact Framework with C#, published by Addison-Wesley. Paul is a Windows Embedded MVP and President of The Paul Yao Company and serves on the board of the Windows Embedded Developers Interest Group.

Show: