Crash course: Asynchronous Programming with async and await

With the .NET Framework 4.5 the new keywords “async” and “await” were introduced. These keywords will aloe an asynchronous programming which is nearly as easy as synchronous programming. With this article I want to give you a crash course into this topic.

Let’s start with a little example. The following source code shows a WPF application with a button click event. Within this event an asynchronous method call is executed.

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        DoSomething(1);

        await DoSomethingAsync(2);

        DoSomething(3);
    }

    private void DoSomething(int x)
    {
    }

    private async Task DoSomethingAsync(int x)
    {
        var task = Task.Run(() => {});

        await task;
    }
}

What will happen within the button click method? At first the method “DoSomething(1)” is executed. As the execution is synchronous, the UI is blocked during this time. Next the method “DoSomethingAsync(2)” is executed. With the “await” keyword we will now return the control to the caller, in this case the UI thread. The method “DoSomethingAsync(2)” will be executed asynchronous. As this method is finished, the remaining part of the calling method is executed and so “DoSomething(3)” is executed.

This little example shows the nice implementation concept of async+await. You can implement your method in the normal synchronous style but by adding the new keywords the execution flow changes to asynchronous.

To create an asynchronous function you have to add the “async” keyword an change the return value to a task. In case you method returns void the Task is without a parameter, otherwise it is a Task where T is type of your return value. The caller can use the returned Tasks variable to check its status. Sometimes you may also have a void as return value. But this is used for fire and forget events only, like in the above example the button clock event.

The async and await keyword will not start an own task. Therefore your method is executed asynchronous only if the called method creates a task and awaits it end. You will see this within the example in method “DoSomethingAsync(2)”. A task is created and started and with the await keyword we wait for the end of the task.

As mentioned above, the big advantage of this implementation pattern is the high similarity of synchronous and asynchronous code. This increases the readability of the otherwise difficult asynchronous method calls. Furthermore it will allow you to change your existing applications from an synchronous to an asynchronous behavior without the need of a refactoring. Of course, the async await pattern will offer some other nice features, like an easy aggregated error handling, but this should not be shown within the context of this crash course. Instead, I want to finish this article with an example how to change existing synchronous code to asynchronous one.

The following source code shows an example of a simple user interface with a button and a text box. On button click a long running calculation is done and the result is shown within a text box.

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Calculate_Click(object sender, RoutedEventArgs e)
    {
        Calculator calculator = new Calculator();
        int result;

        result = calculator.Calculate(5, 7);

        TextBox_Result.Text = result.ToString();
    }
}

public class Calculator
{
    public int Calculate(int a, int b)
    {
        Thread.Sleep(TimeSpan.FromSeconds(3));

        return a + b;
    }
}

During the execution of the calculation the user interface is blocked. Therefore we want to change the implementation to the asynchronous pattern. This can be done with some minor modifications. The long running part is executed within a task. The async and await kewords are added to the calculation method and the return value is changed to Task. Furthermore the async and await keywords are added to the event method too. The following source code shows the modified application.

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private async void Button_Calculate_Click(object sender, RoutedEventArgs e)
    {
        Calculator calculator = new Calculator();
        int result;

        result = await calculator.CalculateAsync(5, 7);

        TextBox_Result.Text = result.ToString();
    }
}

public class Calculator
{
    public async Task<int> CalculateAsync(int a, int b)
    {
        var task = Task.Run(() =>
        {
            Thread.Sleep(TimeSpan.FromSeconds(3));

            return a + b;
        });

        return await task;
    }
}

Now the calculation is executed asynchronous and the user interface stays responsible. All the task management magic is done by the compiler. The source code modifications were marginal and the resulting source code is nearly identical to the origin source code.

Furthermore this example shows another nice feature of the async await pattern. Normally if you execute code in an own task, this task cannot update user interface elements directly. But in this scenario it is working. This nice behavior is possible because the code behind the await statement is executed in the origin context. This default behavior is mainly needed in user interface code and can be disabled in all other cases with the task method “ConfigureAwait(false)”.

Veröffentlicht unter .NET, C#, Crashkurs | Kommentar hinterlassen

Clean Tuples

Depending on the preferences of a developer you may sometimes find a lot of tuples within the source code. Whether this is good or bad practice is another discussion which is not part of this article. Therefore I don’t want to start a discussion whether you shall use classes, structs or tuples. I want to have a look at tuples form the “clean code” point of view.

In my opinion, tuples have one major disadvantage: The code to access tuples is not easy to read. If you use tuples and you write your code they are very easy to use. But in case you have to read, understand and maintain your code after a while or source code which was written by other developers, tuples can become a mess. The following source code shows an easy example. We define a tuple to store information about a person, we create a person tuple in some function and we access the elements of the tuple.

typedef std::tuple<std::string, std::string, int> Person;

Person CreatePerson()
{
  return std::make_tuple("John", "Doe", 35);
}

int _tmain(int argc, _TCHAR* argv[])
{
  Person person = CreatePerson();

  int age = std::get<2>(person);

  std::cout << age << std::endl;

  return 0;
}

This simple example is easy to read. You will understand the source code immediately and you are able to maintain the code. But I think that’s only possible because the whole source code will fit in one screen. What will happen if you use such tuples in a bigger context? The type definition will be placed in one file, the function to create the tuple in another file and the function which access the tuple elements is in a third file. In such a case you will lose the big picture and you need additional time to collect all the information. You cannot longer just read the code, you have to spend time and explore the code to find all needed information.

Have a look at the function to create the tuple. Within this function you have to know that the first parameter is the first name and the second parameter is the last name of the person. Therefore such source code has a high possibility for errors. And on the other hand if you want to use the tuple, you access the elements by an index. In case of the age parameter there is no issue as the used type is unique within the tuple. But if you want to access the first or last name of the person, you will find the same issue like before. Accessing by an index may lead to errors.

As a result of these issues we will think about a possible solution. How can we create clean source code? We found two issues: Creating the tuple and accessing the elements in a clear way. I think a very easy possibility is to exchange the not speaking index number with a speaking enumerator. By using an index enumerator you will be able to set and get the elements of a tuple by using their name. The following source code shows the adapted example.

typedef std::tuple<std::string, std::string, int> Person;

enum PersonIndex
{
  FirstName,
  LastName,
  Age
};

Person CreatePerson()
{
  Person person = std::make_tuple("", "", 0);

  std::get<FirstName>(person) = "John";
  std::get<LastName>(person) = "Doe";
  std::get<Age>(person) = 35;

  return person;
}

int _tmain(int argc, _TCHAR* argv[])
{  
  Person person = CreatePerson();

  int age = std::get<Age>(person);

  std::cout << age << std::endl;

  return 0;
}

This little modification will result in a lot of advantages. You type definition is followed by the according index enumerator which explains the tuple. So you don’t have to explain the tuple with a comment. The creation of the tuple can now be done with an explicit assignment of the parameter name and its value. And the access of the elements will also be done by using the parameter name. The resulting source code is now very easy to understand. You can read the code and will understand it immediately without the need of looking for some more information in other files. For example, it is no longer necessary to look for the type definition and an explanation of the elements. By using the index enumerator you can create “clean” tuples.

Veröffentlicht unter .NET, C++, Clean Code | Kommentar hinterlassen

Design patterns: Singleton

By using the Singleton design pattern you ensure that a class has only one instance. The instance operation is provided by the class itself. So it maintains its own unique instance.

The .NET framework offers a very simple and thread-safe way to create a Singleton. The following source code shows an according example, how to create a singleton instance for logging purposes.

At first we define a interface.

public interface ILogger
{
    void Log(string message);
}

Second we can implement the Singleton object. The class instance is provided by a property which returns a read only object. The .NET framework ensures a thread-safe and lazy creation of the class instance.

public class Logger : ILogger
{
    private static readonly Logger _instance = new Logger();

    private Logger()
    {
    }
           
    public static Logger Instince
    {
        get
        {
            return _instance;
        }
    }            

    public void Log(string message)
    {
        throw new NotImplementedException();
    }        
}

And the last code example shows how to use the Singleton within an demo application.

static void Main(string[] args)
{
    ILogger logger;

    logger = Logger.Instince;

    logger.Log("foo");
}
Veröffentlicht unter .NET, C#, Design Pattern | Kommentar hinterlassen

Dealing with conflicts

In conflict situations it may often be difficult to keep the talk on a solution-oriented way. Personal emotions, different goals of the people, criticism and many other factors will influence the talk. Therefore it is helpful to have a procedure in mind which will guide you through a conflict talk. The following bullet point list will show a very simple procedure for conflict discussion. Try to have this list in mind or write it down as short note and follow this procedure during the talk.

Procedure for a conflict discussion
  • Name the problem (Everyone shall explain his point of view)
  • Find the common goal
  • Search for possible solutions
  • Discuss about the individual concerns against the solutions
  • Find a compromise which covers the collective goals
Veröffentlicht unter Projektleitung | Kommentar hinterlassen

Design patterns: Proxy

The idea of the Proxy design pattern is to provide a substitute for another object were the substitute controls the access to the other project. So there is one real subject with a given interface, for example an object to access a database. And there is a proxy which maintains a reference to this real subject. They both implement the same interface. So the proxy can be used as substitute of the real subject. Often the client does not even know that he uses a proxy.

The proxy controls the access to the real subject and will be responsible for additional tasks, for example creation or deleting of the real subject. The proxy may add some new functionality for example logging, caching, queuing, remote execution or access control.

The following example shows a possible implementation of the Proxy design pattern. Within the example we want to create a class which sends a message to one or some remote listeners. Sending the message may take a while. Therefore the send method will block the client or the client hast to implement asynchronous method calls. Therefore we want to provide a proxy which is responsible for queuing and sending messages. The proxy shall offer the same functionality like the real message provider extended with a queuing mechanism and asynchronous execution of the remote data transfer.

At first we will define the interface for the message channel.

public interface IMessageChannel
{
    void SendMessage(string message);
}

Now we will implement an according class. To simulate the slow remote execution we add a timeout of one second.

public class MessageChannel : IMessageChannel
{
    public void SendMessage(string message)
    {
        Thread.Sleep(TimeSpan.FromSeconds(1));
    }
}

At next we can create the queued message channel which is a proxy of the real message channel. Therefore it holds an instance of the real object and it implements the same interface. To keep it simple we don’t implement the parallel task which executes the sending process. Instead we just add a DoWork method as example of the content of the parallel task.

public class QueuedMessageChannel : IMessageChannel
{
    Queue<string> _messages = new Queue<string>();
    IMessageChannel _messageChannel = new MessageChannel();

    public void SendMessage(string message)
    {
        _messages.Enqueue(message);
    }

    /// <summary>
    /// send the messages
    /// TODO: this must be executed as loop inside a parallel task
    /// </summary>
    private void DoWork()
    {
        string message;

        if (_messages.Count > 0)
        {
            message = _messages.Dequeue();
            _messageChannel.SendMessage(message);
        }
    }
}

Within a console application we can new use the proxy. In this example the client creates the proxy explicitly. If you use a factory instead, the console application will not even know whether it uses a proxy or not. But on execution of the send method you will see the difference as the proxy method will return immediately.

static void Main(string[] args)
{
    IMessageChannel messageChannel;

    messageChannel = new QueuedMessageChannel();

    messageChannel.SendMessage("abc");
    Console.WriteLine("Message was send");

    messageChannel.SendMessage("abc");
    Console.WriteLine("Message was send");

    messageChannel.SendMessage("abc");
    Console.WriteLine("Message was send");

    Console.ReadKey();
}
Veröffentlicht unter .NET, C#, Design Pattern | Kommentar hinterlassen

Write clean code instead of comments

Of course comments help to understand code. They are an essential part of the source code. But comments are an addition only. If you want to create readable and easy to understand source code, you have to focus on the code itself. An obscure implementation cannot be rescued by comments.

But how can we see whether a comment is a helpful addition to the source code or a helpless try to explain bad code. I think there are two main types of comments: the ones explaining “why” something is implemented in this way and the ones explaining “what” is implemented.

A good comment adds additional information to the source code and therefore explains the “why”. Bad comments instead explain “what” is implemented. Without these comments the source code is very hard to understand.

But how can we avoid bad comments and the bad source code they try to explain?

Every time we write a comment we shall ask ourselves: do we explain “what” or “why” we have implemented the code. If the comment explains “what” we have implemented we must try to refactor the source code. In such cases the source code shall be changed to self-explaining code which makes the comment obsolete.

int sellerIdentifier = 15;

//check whether the list of all sales of the seller contains the last sale
if(procuctManager.GetAllSales(sellerIdentifier).Contains(procuctManager.GetLastSale()))
{
	...
}

The comment within the example explains what the source code shall do. The source code itself is hard to read. Without the comment and even with the comment you have to read it several times to understand its behavior.

If you write such code and add the comment, you have to slow down for a moment and think whether the comment explains what the code does or why it is implemented. In this case the comment explains what the code does. So you should think about a possible refactoring. In this case you can remove the comment by using variables. Following you will see a possible refactoring result.

int sellerIdentifier = 15;

List<int> sales = procuctManager.GetAllSales(sellerIdentifier);
int lastSale = procuctManager.GetLastSale();

if(sales.Contains(lastSale))
{
	...
}

As you can see the second version of the source code does not need the comment anymore. Instead you may add a new comment and explain why this function is executed.

Summary

Comments are no substitute for bad code. Bad code stays bad code even if you write a detailed comment explaining each detail. It’s better to spend the time in a refactoring of the bad code then writing long comments.

Veröffentlicht unter .NET, C#, Clean Code | Kommentar hinterlassen

Design patterns: Observer

The Observer design pattern is used when you want to define a one-to-many dependency between objects. In case one object changes its state, all its dependents are notified and updated automatically.

In this design pattern you have two participants. The first one is the observable object, which knows his observers and provides an interface for attaching, detaching and notifying observer objects. The second participant or group of participants is the objects which want to be informed. These observer objects will implement a notification interface which is called by the observable object.

Following I want to show a simple implementation if this design pattern which is not thread-safe. In our example we want to create database connection which has status information. To keep it simple the status information is a string only.  Furthermore we want to create a user interface which shall show the database connection status within the main view and within a status bar. Therefore we have an observable object: the database connection, and several observers: the views.

The notification between the participants is done by events. So we start with an EventArgs class and an interface for the observer classes which contain the event receiver definition.

public class StatusChangedEventArgs : EventArgs
{
    public string Status { get; set; }        
}

public interface IStatusObserver
{
    void StatusChanged(object sender, StatusChangedEventArgs e);
}

At next we can implement a base class for the observable database connection class. As we implement it as abstract base class it can be reused for other observable classes to.

public abstract class StatusObservable
{
    private event EventHandler<StatusChangedEventArgs> _statusChanged;

    public void AttachObserver(IStatusObserver observer)
    {
        _statusChanged += observer.StatusChanged;
    }

    public void DetachObserver(IStatusObserver observer)
    {
        _statusChanged -= observer.StatusChanged;
    }
        
    public void NotifyAllObserver(StatusChangedEventArgs e)
    {
        if (_statusChanged != null)
        {
            _statusChanged(this, e);
        }
    }
}

Based on the observable class we will implement the database connection class. It contains two template methods to connect and disconnect the database. These methods will execute a status change which will trigger the observer notification process.

public class DatabaseConnection : StatusObservable
{
    public void Connect()
    {
        //todo: connect to database

        //change status            
        ChangeStatus("connected");
    }

    public void Disconnect()
    {
        //todo: disconnect from database

        //change status            
        ChangeStatus("disconnected");
    }

    private void ChangeStatus(string status)
    {
        NotifyAllObserver(new StatusChangedEventArgs() { Status = status });
    }
}

Now we can create the two view classes which will observe the database connection. To keep it simple these classes contain the interface implementation only and write the received status update to the console.

public class MainView : IStatusObserver
{
    public void StatusChanged(object sender, StatusChangedEventArgs e)
    {
        Console.WriteLine("MainView - StatusChanged received - new status: " + e.Status);
    }
}

public class StatusBar : IStatusObserver
{
    public void StatusChanged(object sender, StatusChangedEventArgs e)
    {
        Console.WriteLine("StatusBar - StatusChanged received - new status: " + e.Status);
    }
}

To test the implementation we can create a little console application. Within this application we will attach the observers to the observable database connection and execute some methods of this class. The according notifications will be send and shown as output in the console. Before the application gets closed, the observers will be detached from the observable class.

static void Main(string[] args)
{
    //create objects
    DatabaseConnection databaseConnection = new DatabaseConnection();
    MainView mainView = new MainView();
    StatusBar statusBar = new StatusBar();

    //attach observer
    databaseConnection.AttachObserver(mainView);
    databaseConnection.AttachObserver(statusBar);

    //change status in observable object
    databaseConnection.Connect();
    databaseConnection.Disconnect();

    //detach observer
    databaseConnection.DetachObserver(mainView);
    databaseConnection.DetachObserver(statusBar);

    Console.ReadKey();
}
Veröffentlicht unter .NET, C#, Design Pattern | 1 Kommentar