Tag Archives: C# 2012

C# 2012: Anatomy of an Async Method

There are two new keywords added to C# for asynchronous programming: async and await. The async keyword is a modifier for methods, delegates, and lambdas to indicate to the C# compiler that a method might contain async code. It also allows other code to call this method asynchronously. 

If a method doesn’t contain async code, it executes synchronously, but you will receive a warning message from the C# compiler. To run code asynchronously, use the await modifier when executing a method, anonymous method, or lambda. Here’s an example of using async and await keywords to implement an async method:

The async modifier indicates that StartAsync can contain async code. The await modifier calls the DoNetworkCommunicationsAsync method and waits for it to complete. In other words, it awaits the method.

Notice the suffix to the StartAsync method is Async. You aren’t required to add the Async suffix to the method name, but it’s a convention that Microsoft recommends and most developers follow in practice. Another tip on naming conventions refers to methods in earlier versions of .NET that implement EAP and already have the Async suffix—you would name them with the TaskAsync suffix.

To make the example simpler, the return type in the previous example is void, but async methods do have return types other than void. For now, let’s defer discussion of the return type until later, which is an important subject of its own.

The previous example doesn’t have any parameters by design in order to keep it simple. However, async methods can have parameters, but none of the parameters can be ref or out.

As in APM and EAP, as soon as the code calls an async method, with the await modifier, control returns to the caller while the method executes asynchronously. Expanding on the previous method, the following code demonstrates a basic example of how async methods work:

Let’s look at what this code shows in terms of control or what is running when. The specific threading model is defined separately for each .NET technology by a type derived from SynchronizationContext, but this is beyond the scope of this course.

The Main method calls the StartAsync method. Because StartAsync is modified as async, the code will run synchronously until it encounters a call to an async method with the await modifier. As soon as the code calls the method with await, control returns to the calling code Main. So you have two methods running at the same time—Main and StartAsync.

StartAsync continues by calling the DoNetworkCommunicationsAsync method. However, the await modifier makes StartAsync wait until DoNetworkCommunicationsAsync completes. When DoNetworkCommunicationsAsync completes, StartAsync ends. Control was already returned to Main when it encountered the await call to DoNetworkCommunicationsAsync, so StartAsync does not return at the end of the method, it just stops running.

That means that inside of StartAsync, all the code above the awaited method will run synchronously. At the same time, the async method runs. When
DoNetworkCommunicationsAsync completes, control returns to StartAsync and any code following StartAsync executes.

 

JoeMayoThis post is an excerpt from the online courseware for our C# 2012: Asynchronous Programming course written by expert Joe Mayo.

Joe Mayo is an author, independent consultant, and instructor specializing in Microsoft .NET and Windows 8 technology. He has several years of software development experience and has worked with .NET since July 2000.

C# 2012: Debugging Tips

For effective debugging, you need to be able to set a breakpoint. The easiest way to set a breakpoint is to click your mouse in the gutter, which is the vertical space to the left of the editor window, shown in the Figure below.

cswhatsnew

 

The Figure above. Click in the gutter to create a breakpoint.

After setting a breakpoint, you can start debugging by selecting DEBUG|Start Debugging or by pressing the F5 key. This will run the program until it reaches the breakpoint and then stop.

You can customize an individual breakpoint with conditions. Right-click on the red dot in the gutter and you’ll see options for Conditions, Hit Count, and more. You can use Hit Count to stop on the breakpoint after it executes a specified number of times, such as in a loop. Condition, shown in the Figure below, lets you define an expression that will make the code hit a breakpoint on that line when the expression is true.

CS What's New 2

 

The Figure above. You can set conditions on a breakpoint.

After setting a number of breakpoints, you’ll want to organize and keep track of them. You can open the Breakpoints window where you manage breakpoints, shown in the Figure above, by selecting DEBUG|Windows|Breakpoints.

CS What's New 3

 

The Figure above. The Breakpoints window lets you manage breakpoints. From the Breakpoints window, you can create new breakpoints, specify columns to view, and filter the list with Search. You can organize the breakpoints by right-clicking on a breakpoint and selecting Edit labels. Then you can search on labels and perform actions on the entire group of breakpoints as a whole.

When the program stops, you can inspect its state by hovering over variables with a mouse or viewing debugger windows.

 

JoeMayoThis post is an excerpt from the online courseware for our C# 2012: Language Changes and Updates course written by expert Joe Mayo.

Joe Mayo is an author, independent consultant, and instructor specializing in Microsoft .NET and Windows 8 technology. He has several years of software development experience and has worked with .NET since July 2000.

Using Reflection

Reflection gives you the ability to inspect the code of a .NET application and execute that code dynamically. Various tools, such as VS 2012 Web Services and unit testing use reflection to perform actions based on the code you’ve written. When building a Web Service, VS 2012 uses reflection to inspect the attributes applied to classes and then read the method names, parameters, and return types of those methods to build an XML contract for clients to consume.The Unit Test runner uses reflection to find classes that contain tests and execute the methods decorated with test attributes.

Getting Type and TypeInfo

The first step in using reflection is to obtain a Type type or a TypeInfo type. A type is a class, struct, interface, or delegate that you write in order to inspect and learn more about the type. TheType andTypeInfo types let you furtherdelve into the internals of a type, using reflection, to learn about the membersof a type. The Type type has been part of .NET since v1.0. Microsoft introduced the TypInfo type in .NET v4.5, which also supports Windows 8
applications. The difference between Type and TypeInfo in .NET 4.5 is that Type provides reference support and TypeInfo is intended for execution.

If you already have an instance of an object, you can get its Type through the System.Object’s GetType method, like this:

In this example, the code has an instance of Program, prog, making it possible to call GetType to obtain the Type object. TheType object has manymethods for inspecting the type and it contains assembly information. This example prints the Name property, which is Program

Another way to obtain a Type is via the typeof operator. This is a C# operatorfrom basic C# syntax, but now you understand its true purpose and how to use it. Here’s an example:

You give the name of the type to the typeof operator and it returns a Type instance for that type. This example uses the AssemblyQualifiedName, whichgives the fully qualified name of the assembly, as follows:

With a Type, you can get a TypeInfo. Here’s an example:

The example above shows that you must first have a Type, which is testType in this case. With that Type , you can call GetTypeInfo to obtain a TypeInfo .


JoeMayoThis post is an excerpt from the online courseware for our C# 2012: Attributes, Reflections and Dynamic
course written by expert Joe Mayo.

Joe Mayo is an author, independent consultant, and instructor specializing in Microsoft .NET and Windows 8 technology. He has several years of software development experience and has worked with .NET since July 2000.

Using Code-Focused Rapid Application Development (RAD)

There are many visual designers in Visual Studio that allow you to drag-and-drop
controls onto the screen, in what is often referred to as Rapid Application
Development (RAD). However, most applications of any significance require
code that defines the logic of that application. Visual Studio recognizes this by
supporting Code-Focused RAD—tools that help you write code faster. This
section shows a few of the ways you can navigate code, and how to add
snippets and refactor code.

Navigating Code

Visual Studio has several features supporting code navigation, including Call

Hierarchy, Navigate To, Highlighting References, and Live Semantic Errors.
The last two are not really navigation features, but they do help you understand
code better.

Call Hierarchy

Call Hierarchy allows you to view callers and callees to a type member in your
code. You can open the Call Hierarchy window (see Figure 8) by selecting the
type member name you’re interested in and pressing Ctrl+K+T.

RAD

Call Hierarchy lets you view callers and callees to a type member.

The Call Hierarchy window also lets you navigate through code. To navigate
to a specific location, double-click on that location in the Call Hierarchy
window. You can open the branches of the tree by clicking an arrow to view
either Calls To or Calls From the location of the arrow.

Navigate To

Navigate To lets you quickly move to anywhere in your code by typing a
search term. Type Ctrl+, (comma) to display the Navigate To window
shown in the Figure below.

RAD1

The Figure above shows how Navigate To lets you search and move to code quickly.

After the Navigate To window appears, you can type a Search term and all the
matching members will appear in the Results window. You can double-click
any item, or select an item and click the OK button, and Visual Studio will
take you to the right location.

Highlighting References

The Highlighting References feature allows you to select an identifier and
Visual Studio highlights all the references to that identifier. Figure below shows
how this works.

RAD2

The Figure above. Highlight References shows the selected identifier and references.

In the Figure above, we selected the method identifier, Level2. Visual Studio
highlighted the reference to that identifier inside the Main method.

Live Semantic Errors

Live semantic errors show you problems with your code as you type. You can
see compiler errors and warnings without building your code. Figure 11 shows
what a Live Semantic Error looks like.

RAD3

The Figure above. Live Semantic Errors show you problems as you type.

The example in the Figure above is missing an end quote, which is a compiler error.
The Live Semantic Error appears as a squiggly line under the location of the
error. For warnings, you receive a green squiggly line.


JoeMayoThis post is an excerpt from the online courseware for our C# 2012: Visual Studio 2012 IDE
course written by expert Joe Mayo.

Joe Mayo is an author, independent consultant, and instructor specializing in Microsoft .NET and Windows 8 technology. He has several years of software development experience and has worked with .NET since July 2000.