The Fundamental Aims of Asynchrony

async1

C# in Depth, Third Edition

By Jon Skeet

Asynchrony has been a thorn in the side of developers for years. It’s been known to be useful as a way of avoiding tying up a thread while waiting for some arbitrary task to complete, but it’s also been a pain in the neck to implement correctly. In this article, based on chapter 15 of C# in Depth, Third Edition, author Jon Skeet explains the purpose of asynchrony in C#.

At the time of this writing, I’ve been playing with async/await for about two years, and it still makes me feel like a giddy schoolboy. I firmly believe it will do for asynchrony what LINQ did for data handling when C# 3 came out—except that dealing with asynchrony was a far harder problem.

Even within the .NET framework (which is still relatively young in the grand scheme of things), we’ve had three different models to try to make things simpler:

  • The BeginFoo/EndFoo approach from .NET 1.x, using IAsyncResult and AsyncCallback to propagate results
  • The event-based asynchronous pattern from .NET 2.0, as implemented by BackgroundWorker and WebClient
  • The Task Parallel Library (TPL) introduced in .NET 4, but then expanded in .NET 4.5

Despite its generally excellent design, writing robust and readable asynchronous code with the TPL was hard. While the support for parallelism was great, there are some aspects of general asynchrony that are simply much better fixed in a language instead of purely in libraries.

The main feature of C# 5 builds on the TPL so that you can write synchronously looking code that uses asynchrony where appropriate. Gone is the spaghetti of callbacks, event subscriptions and fragmented error handling; instead, asynchronous code expresses its intentions clearly, and in a form that builds on the structures developers are already familiar with. A new language construct allows you to “await” an asynchronous operation. This “awaiting” looks very much like a normal blocking call, in that the rest of your code won’t continue until the operation has completed, but it manages to do this without actually blocking the currently executing thread. Don’t worry if that statement sounds completely contradictory.

The .NET framework has embraced asynchrony wholeheartedly in version 4.5, exposing asynchronous versions of a great many operations, following a newly documented task-based asynchronous pattern to give a consistent experience across multiple APIs. The WinRT framework used to create applications for Windows 8 enforces asynchrony for all long-running (or potentially long-running) operations. In short, the future is asynchronous and you’d be foolish not to take advantage of the new language features when trying to manage the additional complexity.

Just to be clear, C# hasn’t become omniscient, guessing where you might want to perform operations concurrently or asynchronously. The compiler is smart, but it doesn’t even attempt to remove the inherent complexity of asynchronous execution. You still need to think carefully, but the beauty of C# 5 is that all the tedious and confusing boilerplate code that used to be required has gone. Without the distraction of all fluff required just to make your code asynchronous to start with, you can concentrate on the hard bits.

A word of warning: this topic is reasonably advanced. It has the unfortunate properties of being incredibly important (realistically, even entry-level developers will need to have a passing understanding of it in a few years) but also quite tricky to get your head round to start with. I’m not going to shy away from the complexity; we’ll look at what’s going on in a fair amount of detail.

It’s just possible that I may temporarily break your brain a little, before hopefully putting it back together again later on. If it all starts sounding a little crazy, don’t worry—it’s not just you; bafflement is an entirely natural reaction. The good news is that when you’re using C# 5, it all makes sense on the surface. It’s only when you try to think of exactly what’s going on behind the scenes that things get tough.

Let’s get started!

Introducing asynchronous functions

C# 5 introduces the concept of an asynchronous function. This is always either a method or an anonymous function[1] which is declared with the async modifier, and can include await expressions. These await expressions are the points where things get interesting from a language perspective: if the value that the expression is awaiting isn’t available yet, the asynchronous function will return immediately, and then continue where it left off (in the “right” thread) when the value becomes available. The natural flow of “don’t execute the next statement until this one has completed” is still maintained, but without blocking.

We’ll break that woolly description down into more concrete terms and behavior later on, but you really need to see an example of it before it’s likely to make any sense.

First encounters of the asynchronous kind

Let’s start with something very simple, but which demonstrates asynchrony in a practical way. We often curse network latency for causing delays in our real applications, but it does make it easy to show why asynchrony is so important, as we can see in 1.

Listing 1 Displaying a page length asynchronously

class AsyncForm : Form
{
    Label label;
    Button button;

    public AsyncForm()
    {
        label = new Label { Location = new Point(10, 20), Text = “Length” };
        button = new Button { Location = new Point(10, 50), Text = “Click” };
        button.Click += DisplayWebSiteLength;  // #1
        AutoSize = true;
        Controls.Add(label);
        Controls.Add(button);
    }

    async void DisplayWebSiteLength(object sender, EventArgs e)
    {
        label.Text = “Fetching...”;
        HttpClient client = new HttpClient();  // #2
        string text = await client.GetStringAsync(“http://csharpindepth.com”);  // #2
        label.Text = text.Length.ToString();  // #3
    }
}

Application.Run(new AsyncForm());laying a page length asynchronously

#1 Wires up event handler

#2 Starts fetching the page

#3 Updates the UI

The first part of listing 1 simply creates the UI and hooks up an event handler for the button in a straightforward way. It’s the DisplayWebSiteLength method that we’re interested in. When you click on the button, the text of the book’s home page is fetched, and the label is updated to display the HTML length in characters.

I could have written a smaller example program as a console app, but hopefully this makes a more convincing demo. In particular, if you remove the async and await contextual keywords, change HttpClient to WebClient, and change GetStringAsync to DownloadString, the code will still compile and work… but the UI will freeze while it fetches the contents of the page.[2] If you run the async version (ideally over a slow network connection), you’ll see that the UI is responsive; you can still move the window around while the web page is fetching.

Most developers are familiar with the two golden rules of threading in Windows Forms development:

  • Don’t perform any time-consuming action on the UI thread
  • Don’t access any UI controls other than on the UI thread

These are easier to state than to obey. As an exercise, you might want to try a few different ways of creating similar code to listing 1 without using the new features of C# 5. For this extremely simple example, it’s not actually too bad to use the event-based WebClient.DownloadStringAsync method, but as soon as more complex flow control (error handling, waiting for multiple pages to complete, and so on) comes into the equation, the “legacy” code quickly becomes hard to maintain, whereas the C# 5 code can be modified in a natural way.

At this point, the DisplayWebSiteLength method feels somewhat magical: we know it does what we need it to, but we have no idea how. Let’s take it apart just a little bit, saving the really gory details for later.

Breaking down the first example

First I’ll start by expanding the method very slightly – splitting the call to HttpClient.GetStringAsync from the await expression to highlight the types involved:

async void DisplayWebSiteLength(object sender, EventArgs e)
{
    label.Text = “Fetching...”;
    HttpClient client = new HttpClient();
    Task<string> task = client.GetStringAsync(“http://csharpindepth.com”);
    string text = await task;
    label.Text = text.Length.ToString();
}

Notice how the type of task is Task<string>, but the type of the await task expression is just string. In this sense, an await expression performs an “unwrapping” operation, at least when the value being awaited is a Task<TResult>. (You can await other types too, as we’ll see, but Task<TResult> acts as a good starting point.) That’s one aspect of await – which doesn’t seem directly related to asynchrony, but makes life easier.

The main purpose of await is to avoid blocking while we wait for time-consuming operations to complete. You may be wondering how this all works in the concrete terms of threading. We’re setting label.Text at both the start and end of the method, so it’s reasonable to assume that both of those statements are executed on the UI thread, and yet we’re clearly not blocking the UI thread while we wait for the web page to download.

The trick is that the method actually returns as soon as we hit the await expression. Up until that point, it executes synchronously on the UI thread just as any other event handler would. If you put a breakpoint on the first line and hit it in the debugger, you’ll see that the stack trace shows that the button is busy raising its Click event. When we reach the await, the code checks whether the result is already available, and if it’s not (which will almost certainly be the case) it schedules a continuation to be executed when the web operation has completed. A continuation is effectively a callback which maintains the control state of the method: just as a closure maintains its environment in terms of variables, a continuation also remembers where it had got to, so it can continue from there when it’s executed. It’s very much like an iterator block, except that instead of yielding a value and then waiting to be executed again, await just “pauses” the method until the asynchronous operation has completed.[3]

In our case, the continuation executes the rest of the method, effectively jumping to the end of the await expression, back in the UI thread just as we want in order to manipulate the UI.

In case you’re wondering, all of this is handled by the compiler creating a complicated state machine. That’s an implementation detail. It’s instructive to examine it to get a better grasp of what’s going on, but before that, we need a more concrete description of what we’re trying to achieve and what the language actually specifies.

Thinking about asynchrony

If you ask a developer what they understand by asynchronous execution, chances are they’ll start talking about multi-threading. While that’s an important part of uses of asynchrony, it’s not really required for asynchronous typical execution. To fully appreciate how the async feature of C# 5 works, it’s best to strip away any thoughts of threading, and go back to basics.

Asynchrony strikes at the very heart of the execution model that C# developers are familiar with. Consider simple code like this:

Console.WriteLine(“First”);

Console.WriteLine(“Second”);

We expect the first call to complete, and then the second call to start. Execution flows from one statement to the next, in order. An asynchronous execution model doesn’t work that way. Instead, it’s all about continuations. When you start doing something, you tell that operation what you want to happen when that operation has completed. You may have heard (or used) the term callback for the same idea, but that’s got a broader meaning than the one we’re after here. We’re only interested in preserving the control state of the program, not arbitrary callbacks for other purposes.

Continuations are naturally represented as delegates in .NET, typically actions that receive the results of the asynchronous operation. That’s why to use the asynchronous methods in WebClient prior to C# 5, you would wire up various events to say what code should be executed in the case of success, failure and so on. The trouble is that creating all those delegates for a complicated sequence of steps ends up being very complicated, even with the benefit of lambda expressions. It’s even worse when you try to make sure that your error handling is correct. (On a good day, I can be reasonably confident that the success paths of hand-written asynchronous code are correct. I’m typically less certain that it reacts the right way on failure.)

Essentially, all that async in C# does is ask the compiler to build continuations for you. For an idea that can be expressed so simply, however, the consequences for readability and developer sanity are remarkable.

When I wrote earlier that we pass the continuation to the asynchronous operation at the same time that we start it, I was thinking about asynchrony in a classic, idealized sense. The reality in the task-based asynchronous pattern is very slightly different. Instead of the continuation being passed to the asynchronous operation, the asynchronous operation starts and returns us a token we can used to provide the continuation later. It represents the ongoing operation, which may have completed even before it’s returned to the calling actually code or may still be in progress. That token is then used whenever we want to express the idea of “I can’t proceed any further until this operation has completed.” Typically the token is in the form of a Task or Task<TResult>, but it doesn’t have to be.

So, the execution flow in an asynchronous method in C# 5 is typically along the lines of:

  • Do some work
  • Start an asynchronous operation, and remember the token it returns
  • Possibly do some more work. (Often you really can’t make any further progress until the asynchronous operation has completed, in which case this step is empty.)
  • “Wait” for the asynchronous operation to complete (via the token)
  • Do some more work
  • Finish

If we didn’t care about exactly what the “wait” part meant, we could do all of this in C# 4. If we’re happy to block until the asynchronous operation completes, the token will normally provide us some way of doing so. For a Task, we could just call Wait(). At that point, though, we’re taking up a valuable resource (a thread) and not doing any useful work. It’s a little like phoning for a takeaway pizza, and then standing at the front door until it arrives. What we really want to do is get on with something else, ignoring the pizza until it arrives. That’s where async comes in.

When we “wait” for an asynchronous operation, what we’re really saying is, “I’ve gone as far as I can go for now. Keep going when the operation has completed.” But if we’re not going to block the thread, what can we do? Very simply, we can return right there and then. We’ll continue asynchronously ourselves. And if we want our caller to know when our asynchronous method has completed, we’ll pass a token back to them, which they can block on if they want, or (more likely) use with another continuation. Very often you’ll end up with a whole stack of asynchronous methods calling each other. It’s almost as if you go into “async mode” for a section of code. There’s nothing in the language which states that it has to be done that way, but the fact that the same code which makes consuming asynchronous operations also behaves as an asynchronous operation certainly encourages it.

With the theory out of the way, let’s take a closer look at the concrete details of asynchronous methods. Asynchronous anonymous functions fit into the same mental model, but it’s much easier to talk about asynchronous methods.

Modelling asynchronous methods

I find it very useful to think about asynchronous methods in the form of figure 1.

async2

Figure 1 Async model

Here we have three blocks of code (the methods) and two boundaries (the method return types). To give a very simple example, we might have:

static async Task<int> GetPageLengthAsync(string url)
{
    HttpClient client = new HttpClient();
    Task<string> fetchTextTask = client.GetStringAsync(url);
    int length = await fetchTextTask;
    return length;
}

static void PrintPageLength()
{
    Task<int> lengthTask = GetPageLengthAsync(“http://csharpindepth.com”);
    Console.WriteLine(lengthTask.Result);
}

Here the five parts of the diagram correspond like this:

  • The calling method is PrintPageLength.
  • The async method is GetPageLengthAsync.
  • The asynchronous operation is HttpClient.GetStringAsync.
  • The boundary between the calling method and the async method is Task<int>.
  • The boundary between the async method and the asynchronous operation is Task<string>.

We’re mainly interested in the async method itself, but I’ve included the other methods so we can work out how they all interact together. In particular, you definitely need to know about the valid types at the method boundaries.

Summary

I hope that the more complicated, deep-dive sections of this chapter haven’t put you off the elegance of the asynchronous features of C# 5. The ability to write efficient asynchronous code in a more familiar execution model is a huge step forward, and I believe it will be transformative—once it’s well understood. In my experience giving presentations about async, many developers get easily confused by the feature the first time they see and use it. That’s entirely understandable, but please don’t let that put you off.



Here are some other Manning titles you might be interested in:

async 3

Dependency Injection in .NET

Mark Seemann

async 4

Windows Phone 7 in Action

Timothy Binkley-Jones, Massimo Perga and Michael Sync

async5

Real-World Functional Programming

Tomas Petricek

 

[1] As a reminder, an anonymous function is either a lambda expression or an anonymous method.

[2] HttpClient is in some senses the “new and improved” WebClient—it’s the preferred HTTP API for .NET 4.5 onwards and only contains asynchronous operations. If you’re writing a Windows Store app, you don’t even have the option of using WebClient.

[3] There are many parallels to be drawn between iterator blocks and asynchronous functions, but don’t be fooled into thinking they’re equivalent features. In the past, asynchronous libraries have been built on top of iterators to take advantage of the generated state machines, but the fact that asynchronous functions have been designed specifically for asynchrony makes them considerably cleaner.

 

del.icio.us Tags: ,,,

The Building Blocks of a F# Markdown Parser

by Tomas Petricek, author of F# Deep Dives

Editor’s Note: The F# Deep Dives MEAP will be 50% on December 18, 2012. Use code dotd1218au at checkout.

Markdown is a simple text-based markup language that can be used to produce clean HTML and is used by sites such as StackOverflow or GitHub. You can build your very own an efficient parser that can be extended with custom features and that allows you to process the document after parsing. In this article, based on chapter 11 of F# Deep Dives, author Tomas Petricek describes the key elements of such a project, in particular, the representation of a Markdown document.

I’ve been writing a blog for a number of years now. Since the beginning, I wanted the website to use clean and simple HTML code. Initially, I just wrote articles in HTML by hand, but then I became a big fan of Markdown, a simple text-based markup language that can be used to produce clean HTML and is used by sites such as StackOverflow or GitHub. However, none of the existing Markdown implementations supported what I wanted: I needed an efficient parser that can be extended with custom features and that allows me to process the document after parsing. That’s why I decided to write my own parser in F#.

In this article, I’ll describe the key elements of the project. In particular, I’ll discuss the key subject from a functional perspective: the representation of a Markdown document.

You might not need to implement your own text-formatting engine, but you may often face a similar task. Text processing is not only useful when working with external files (test scripts, behavior specifications, or configuration files) but also when processing user inputs in an application (such as commands or calculations).

Introducing the Markdown format

The Markdown format is a markup language that has been designed to be as readable as possible in the plain text form. It is inspired by formatting marks, such as *emphasis*, that are often used in text files, emails, or README documents. It specifies the syntax precisely and thus it is possible to translate Markdown documents to HTML.

Formatting text with Markdown

The formatting of Markdown documents is based on whitespace and common punctuation marks. The document consists of block elements (such as paragraphs, headings, and lists). A block element can contain emphasized text, links, and other formatting. The following sample demonstrates some of the syntax:

Visual F#  
=========
F# is a **programming language** that supports _functional_, as 
well as _object-oriented_ and _imperative_ programming styles. 
Hello world can be written as follows: 

    printfn "Hello world!" 

For more information, see the [F# home page] (http://fsharp.net) or 
read [Real-World Functional Programming](http://manning.com/petricek) 
published by [Manning](http://manning.com).

The document above consists of four block elements. It starts with a heading. The separator "=" is used for first level headings. We can also create second level headings using "-" as a separator. An alternative style uses a certain number of "#" characters at the beginning of the line, so, for example, ## Example is a second-level heading.

The second block is a paragraph, followed by a code sample and one more paragraph. The text in paragraphs is formatted using ** (strong) and _ (emphasis). Both asterisk and underscore can be used for strong and emphasized text—one character means emphasis and two characters means strong text. We can also create hyperlinks, which is demonstrated by the last line.

From a programming language perspective, formats such as Markdown can be viewed as domain specific languages, which is explained in the following sidebar.

Meta: external domain specific languages

The term domain specific languages (DSLs) refers to programming languages that are designed to solve problems from a particular domain or field. DSLs are useful when you need to solve a large number of problems of the same class. In that case, the time spent on developing the DSL will be balanced out by the time that you save when using the DSL to solve particular problems.

DSL can be categorized into two groups. Internal DSLs are embedded in another language (like F# or C#). Functions from the List module with the pipelining operator (|>) can be viewed as a DSL. They solve a specific problem—list processing—and solve it very well without other dependencies.

External DSLs are languages that are not constructed on top of other languages. They may be used as embedded strings (for example, regular expressions or SQL) or as standalone files (including Markdown, configuration files, Makefile, or for example, behavior specifications using language such as Cucumber).

Now that I’ve introduced the Markdown format and domain specific languages in general, let’s look at a number of benefits that we can expect from a Markdown parser written in F#.

Why another Markdown parser?

Markdown is a well-established format and there is a number of existing tools that convert it to HTML. Most of these are written using regular expressions and there are some written for almost any platform, including .NET. So, why do we need yet another processor? Here are a few reasons:

  • Creating a custom syntax extension for Markdown is quite difficult when using an implementation based on regular expressions. It is hard to find where the syntax is being processed, and changing a regular expression can lead to various unexpected interactions.
  • Most of the tools transform Markdown directly to HTML. This makes it hard to add a custom-processing step, for example, to process all code samples in the document before generating HTML.
  • A related problem is that HTML is the only supported output. What if we wanted to turn Markdown documents into another document format, such as Word or LaTeX?
  • Finally, performing a single regular expression replacement may be quite efficient, but, if the processor performs a huge number of them, the code can get quite CPU consuming. A custom implementation may give us better performance.

Let’s now look how we can achieve these goals using F#. The key element of the solution is an elegant functional representation of the document structure.

Representing Markdown documents

When solving problems in functional languages, the first question we need to answer often is: "What data structures do we need to represent the data we work with?" In case of Markdown processor, the data structure represents a document. As discussed earlier, a document consists of blocks of different kinds. Some of the blocks (like paragraphs) may contain additional inline formatting and hyperlinks.

fdeep101

Figure 1 Here you can see how different MarkdownBlock elements and different MarkdownSpan elements are used to format the sample document. All other unmarked text is represented as Literal.

Listing 1 Representation of Markdown document

type MarkdownDocument = list

and MarkdownBlock =  
  | Heading of int * MarkdownSpans
  | Paragraph of MarkdownSpans
  | CodeBlock of list

and MarkdownSpans = list

and MarkdownSpan =  
  | Literal of string
  | InlineCode of string
  | Strong of MarkdownSpans
  | Emphasis of MarkdownSpans
  | HyperLink of MarkdownSpans * string

The types that model Markdown documents are shown and explained in listing 1. I defined the types as a mutually recursive using the and keyword for two reasons. Firstly, the MakdownSpans and MarkdownSpan types are mutually recursive and they both reference each other. Secondly, I wanted to start with a type that represents the entire document rather than starting from the span to make the explanation easier to follow.

Summary

Broadly speaking, this article was about external domain specific languages. An external DSL is a small programming language or document format that has its own syntax and represents some script, document, or command. External DSLs can be used to configure an application, to provide scripting capabilities, customization, and various other tasks.

The domain specific language that we focused on was the Markdown document format. When working with external DSLs, we first write an F# representation of the language and then implement processing of the DSL.

The functional representation that I described in this article is the cornerstone of a new Markdown processor. Other components are all built around this representation. Chapter 3 of F# Deep Dives looks at three additional aspects: writing a parser that turns text into MarkdownDocument, writing an HTML generator that turns MarkdownDocument into a HTML file, and implementing the pre-processing of a document that generates the references section with all of the document links. All of these tasks are built on top of a simple representation using powerful F# features like pattern matching and active patterns.

1. The project can be found at https://github.com/tpetricek/FSharp.Formatting

2. For more information about Markdown, see http://daringfireball.net/projects/markdown

Here are some other Manning titles you might be interested in:

fdeep102

The Real-World Functional Programming

Tomas Petricek with Jon Skeet

fdeep103

HTML5 for .NET Developers

Jim Jackson II and Ian Gilman

fdeep104

IronPython in Action

Michael J. Foord and Christian Muirhead

 

del.icio.us Tags: ,,,

“Hello, World” Aspect

 

AOP in .NET
By Matthew Groves
Aspect-oriented programming is a technique that is complementary to object-oriented programming (OOP). The goal of AOP is to reduce repetitive, boilerplate code. This article, based on AOP in .NET, walks you through a very basic "Hello, World" example of using AOP in .NET. He breaks apart that example and identifies the individual puzzle pieces and how they fit together into something called an "aspect."

“Hello, World” Aspect

If you’ve never done aspects, we’ll give you a taste of what’s in store. Don’t worry if you don’t fully understand what’s going on just yet. Follow along just to get your feet wet. I’ll be using Visual Studio 2010 and PostSharp. Visual Studio Express (which is a free download) should work too. I’m also using NuGet, which is a great package manager tool for .NET that integrates with Visual Studio. If you’ve never used NuGet, you should definitely take a few minutes to check it out at NuGet.org and install it: it will make your life as a .NET developer much easier.

Start by selecting File>New Project and then Console Application. Call it whatever you want, but I’m calling mine "HelloWorld". You should be looking at an empty console project like so:

class Program {
    static void Main(string[] args) {
    }
}

Next, install PostSharp with NuGet. NuGet can work from a PowerShell command-line within Visual Studio, called Package Manager Console. To install PostSharp via the Package Manager Console, just use the Install-Package command.

Listing 1 Installing PostSharp with NuGet PowerShell console
PM> Install-Package postsharp
Successfully installed 'PostSharp 2.1.6.17'.
Successfully added 'PostSharp 2.1.6.17' to HelloWorld.

Alternatively, you can do it via the Visual Studio UI by first right-clicking on References in Solution Explorer.

image

Figure 1 Starting NuGet with the UI

Select Online, search for PostSharp, and click Install.

image

Figure 2 Search for PostSharp and install with NuGet UI

You may get a PostSharp message that asks you about licensing. Accept the free trial and continue. The Starter Edition is free for commercial use, so you can use it for free at your job too. Now that PostSharp is installed, you can close out of the NuGet dialog. In Solution Explorer under References, you should see a new PostSharp reference added to your project.

Now you’re ready to start writing your first aspect.

Create a class with one simple method that just writes to Console. Mine looks like this:

public class MyClass {
    public void MyMethod() {
        Console.WriteLine("Hello, world!");
    }
}

Instantiate this inside of the Main method,and call the method. Here’s what the Program class should look like now:

class Program {
    static void Main(string[] args) {
        var myObject = new MyClass();
        myObject.MyMethod();
    }
}

Execute that program now (F5 or CTRL+F5 in Visual Studio), and your output should look like this:

image

We’re not really pushing the limits of innovation just yet, but hang in there!

Now, create a new class that inherits from OnMethodBoundaryAspect, which is a base class in the PostSharp namespace. Something like this:

Listing 2 The first step in using the PostSharp API – derive from OnMethodBoundaryAspect
[Serializable]
public class MyAspect : OnMethodBoundaryAspect {
}

PostSharp requires aspect classes to be serializable (this is because PostSharp instantiates aspects at compile time, so they can be persisted between compile time and run time).

Congratulations, you just wrote an aspect, even though it doesn’t do anything yet. Like the name implies, this aspect allows you to insert code on the boundaries of a method. Let’s make an aspect that inserts code before and after a method gets called. Start by overriding the OnEntry method. Inside of that method, write something to Console, like this:

Listing 3 Override the OnEntry method to add some functionality
[Serializable]
public class MyAspect : OnMethodBoundaryAspect {
    public override void OnEntry(MethodExecutionArgs args) {
        Console.WriteLine("Before the method");
    }
}

Notice the MethodExecutionArgs parameter. It’s there to give information and context about the method being bounded. We won’t use it in this simple example, but argument objects like that are almost always used in a real aspect. Create another override, but, this time, override OnExit.

Listing 4 Override the OnExit to add more functionality
[Serializable]
public class MyAspect : OnMethodBoundaryAspect {
    public override void OnEntry(MethodExecutionArgs args) {
        Console.WriteLine("Before the method");
    }
    public override void OnExit(MethodExecutionArgs args) {
        Console.WriteLine("After the method");
    }
}

Now you have written an aspect that will write to Console before and after a method. But, which method? The most basic way to tell PostSharp which method (or methods) to apply this aspect to is to use the aspect as an attribute on the method. For instance, to put it on the boundaries of the earlier "Hello, World" method, just use it on the method like so:

Listing 5 Apply the aspect to a method by using an attribute
public class MyClass {
    [MyAspect]
    public void MyMethod() {
        Console.WriteLine("Hello, world!");
    }
}

Now, run the application again (F5 or CTRL+F5). You should see an output like this:

image

Figure 4 Output with MyAspect applied

That’s it. You’ve now written an aspect and told PostSharp where to use that aspect. This example may not seem that impressive, but notice that you were able to put code around the method without making MyMethod any changes to MyMethod itself. Yeah, you did have to add that [MyAspect] attribute, but there are more efficient and/or centralized ways of applying PostSharp aspects.

 

Here are some other Manning titles you might be interested in:

image

Spring in Action, Third Edition

Craig Walls

image

Spring in Practice

Willie Wheeler, John Wheeler, and Joshua White

image

Spring Integration in Action

Mark Fisher, Jonas Partner, Marius Bogoevici, and Iwein Fuld

 

 

Mastodon
github.com/alvinashcraft