RabiesI’ve always been fascinated by incongruous or confusing signage. This one is from Tintagel in Cornwall. I assume that if you see someone with rabies, you can jam the ring down on his head to make it harder for him to bite you?

Tagged with:

St. Ives BeachI just got back from England a few days ago, which is why I haven’t posted in a few weeks. We spent about a week in Cornwall in St. Ives (the picture is a view from just outside our room at the Pedn Olva hotel there), and then a week in London, visiting family and wandering about.

By the way, there are several St. Ives in the UK, so it is not entirely clear whether the riddle refers to this one or not.

Cornwall is beautiful. I’ve included a few photos below.

This is St Michael's Mount near Marazion, Cornwall, a couple of miles from Penzance (as in the Pirates of).

This is St Michael’s Mount near Marazion, Cornwall, a couple of miles from Penzance (as in the Pirates of). You can walk to the island when the tide is out, but have to take a boat the rest of the time. The castle has been continuously populated for something like 350 years, but (if your lungs and legs can handle the climb), you can tour parts of the building.

Gardens on St. Michael's Mount

There are also some really cool gardens on the island, although you have to pay extra to see them–and do a lot of climbing!

Land's End

This is a shot from Land’s End, which is the western-most point of England.

Lost Gardens of Heligan

This is one of the sculptures from The Lost Gardens of Heligan. These were Victorian gardens that had basically disappeared, but were uncovered during the hurricane in 1990. Since then, a lot of restoration work has been going on. They are well worth a visit, but if you drive, be warned that some of the two-way roads don’t seem wide enough for a bike path…

Tintagel

We also visited the ruins at Tintagel, which has a legendary connection with King Arthur (although the castle is 700 years too late, the legend says that he was born in the area).

Tintagel View

There is a lot of climbing to do at Tintagel too, but it is worth it for the view! While we were there, some poor woman fell and broke her foot. The paramedics had to squeeze up narrow staircases with all their gear, and eventually they ended up calling in a helicopter to evacuate her away from the top.

 

 

Tagged with:

David's DeskMy friend and co-worker David is responsible for building mobile applications, so his desk tends to be a bit busy. Aside from his Windows laptop and his Mac for OSX development, he tends to have several tablets and phones on his desk.

Given that, it seemed only natural to add a few additional devices from my collection to see if he would extend support…

Bonus points to anyone who can name all of the devices on the desk!

ScrabbleThis is about one of my favorite practical jokes.

At one of the companies where I used to work, there was a big table where people tended to play games during lunch, including a group of dedicated scrabble players.

I felt that the game was getting a little too easy, so one evening I went out and purchased 3 additional sets that were identical to the one they used, and replaced a significant number of the consonants with Es from the other sets.

The following day, I watched the game unfold. About 20 minutes in, the game was still going, but one of the players waved me over to show me how terrible his luck was — he had an I and 6 Es! I commiserated, and wondered if he had done any counting, since there were at least 10 Es on the board already, and a full set should only have 12!

It took almost half an hour before they finally tumbled, at which point I had to make a run for it (our department was well armed with Nerf weaponry)!

The simple jokes are often the best! I think I just about ruptured something trying not to laugh while the game went on.

After that, they locked up the Scrabble game to keep it safe. Silly really, since I am very good at picking locks :-).

3D Printer at SAMSI was just in Sam’s club, and took this picture. I guess if you can buy a 3D printer in conventional brick-and-mortar stores, it must be becoming pretty mainstream.

The printer they are selling is the MakerBot Replicator Mini, which is considered to be a good (if slightly expensive) entry machine. The Sam’s club price was $1200, which is a couple of hundred dollars cheaper than MSRP.

Biggest complaints I’ve heard about it are the small size (3.9″ x 3.9″ x 4.9″) and that it is relatively slow. On the other hand, it looks really cool, and has a built-in camera so you can check on progress remotely!

Sam’s is also selling filament in 4 colors.

Tagged with: , ,

In a previous post, I demonstrated a convenient way to make a wait cursor show up during “reasonably” long operations (up to a few seconds). For anything longer than that, though, a wait cursor won’t cut it — for one thing, your UI will become unresponsive. For another, there is no way (other than killing your app) for the user to stop a long process.

There are tons of different ways to provide feedback and cancel options, but until .NET 4.5/4.6, they were all a little bit kludgy. Now, thanks to async handling, it is possible to provide progress, keep your app responsive, and to do it in a way that is quite elegant.

There is quite a lot to async handling, but I wanted to provide as simple an example as I could for offloading work into another thread in such a way as to show progress and allow canceling. Here is what my application looks like:

Async Progress

Not much too it – you click the start button to start the process running, progress is shown until you either get a completed message, or you hit the cancel button (which is the same button, re-purposed). The “work” being done is just a simple loop with a sleep:

for (int i = 0; i < 100; i++)
{
  Thread.Sleep(200);
}

The reason for the loop and the smaller sleep duration (rather than just sleeping for 20000 milliseconds) is so that we can easily report progress by updating the progress bar, and also so we can check to see if the user has hit the cancel button. This will be more obvious in a bit. Almost all of the handling takes place in the button click handler. I’ll show the full code first, then break it down.

private bool m_running = false;
CancellationTokenSource m_cancelTokenSource = null;

private async void button_Click(object sender, EventArgs e)
{
  if (!m_running)
  {
    m_running = true;
    statusLabel.Text = "Working";
    button.Text = "Cancel";
    Progress<int> prog = new Progress<int>(SetProgress);
    m_cancelTokenSource = new CancellationTokenSource();
    try
    {
      await SlowProcess(prog, m_cancelTokenSource.Token);
      statusLabel.Text = "Done";
    }
    catch (OperationCanceledException)
    {
      statusLabel.Text = "Canceled";
    }
    finally
    {
      button.Text = "Start";
      m_running = false;
      m_cancelTokenSource = null;
    }
  }
  else
  {
    statusLabel.Text = "Waiting to cancel...";
    m_cancelTokenSource.Cancel();
  }
}

Some of the code here is related to handling the button and label text, making it show the appropriate message at the appropriate time. There is also an m_running flag that is just used to handle the button switch from a “Start” button to a “Cancel” button and back again. If we want to boil the code down to just the minimum required to cause the operation to be launched as an async operation (meaning that the work will happen on another thread), we really just need this:

private async void button_Click(object sender, EventArgs e)
{
  statusLabel.Text = "Working";
  await SlowProcess();
  statusLabel.Text = "Done";
}

We technically don’t need to update the label either, but it will make the explanations simpler. There are two really important things going on with this code. First is the presence of the “async” keyword in the method signature. This tells .NET that this method is going to make some sort of asynchronous call. Second is the “await” in front of our call to SlowProcess().

If SlowProcess() was just a regular method (it’s not, but we’ll come back to that), you could easily imagine that this code would work fine without the async/await calls. The label would change to Working, the work would be done, then the label would be changed to Done.  However, our UI would be completely locked during the SlowProcess() handling because the system would not get any cycles.

By adding await, we are instructing the system to launch the work in SlowProcess() on another thread, which means that the main thread will not be locked.  Prior to .NET 4.5, you might have done this by explicitly launching the work on another thread. Something like:

ThreadPool.QueueUserWorkItem(SlowProcess);

But there is something strange going on here — if you just launched a new thread, once the item was queued, execution would continue on to the next line of code. The label would change to “Working”, then almost immediately change to “Done”, because launching the work on a new thread takes almost no time. Of course, nothing is really done at this point — the work is going on in another thread. With the old mechanisms, that thread would have to signal back to the main thread when it was really done, and it couldn’t just update the UI because you would get a nasty cross-thread error (you can’t update UI elements created from one thread in another thread).

This is where the magic of async comes in. Because this is an async method, the compiler effectively breaks up the code for you. When the await is hit, the process is launched, but then control is returned from the method — as if there were a “return” statement right after the thread launch. But, when the processing in the other thread is complete, execution is returned back to this statement, and execution continues on to the next statement! The steps look something like this:

  1. User clicks on the button, causing the button_Click method to be called.
  2. Label is changed to read “Working”.
  3. Thread is launched to execute the SlowProcess() code.
  4. Control is returned from the button_Click method, meaning that processing can continue.
  5. At some point in the future, SlowProcess() completes.
  6. Call is made back into the button_Click method, immediately after the async call.
  7. Label is changed to read “Done”.

In the example above, SlowProcess() just does some work, but it could have returned a value as well:

int result = await SlowProcess(prog, m_cancelTokenSource.Token);

There are also ways in which we could have launched work on multiple threads simultaneously, and the code would have auto-magically continued only when all of the work was completed. That is beyond the scope of this article, but the power of async is really impressive, and we are just scratching the surface right now.

Progress

Let’s get back to some of the other things that we want to handle, starting with progress. If you recall, in our original code, we created a Progress object, which we then passed to the SlowProcess() method:

Progress<int> prog = new Progress<int>(SetProgress);
await SlowProcess(prog, m_cancelTokenSource.Token);

Progress is a system class that implements the IProgress<T> interface. In this case, we want to update progress with an integer, so we are using int for our T, but it could be anything. SetProgress is the name of the method we want to call when progress needs to be updated, and it looks like this:

private void SetProgress(int value)
{
    progressBar.Value = value + 1;
}

Note that this method takes an argument of type int, which matches the generic type we’ve specified for our Progress object. In the SlowProcess() code that is actually doing the work, every now and then we want to have SetProgress() be called to indicate our current status. However, we can’t just call SetProgress() because of cross-threading issues. We could manually handle that, but we don’t need to. Instead, in SlowProcess() we can just add a call like:

prog.Report(i);

Where prog is a reference to our Progress<int> object and i is the loop variable we are using that indicates how far we are in to the process. When Report() is called, a call is made to SetProgress, automatically marshaled to the correct thread. SetProgress() then just updates the progress bar’s position.

 Canceling

We also have support for canceling the operation when the user hits the cancel button. There are actually two separate classes involved with cancelling:

  • CancellationTokenSource
  • CancellationToken

We create and hold on to a CancellationTokenSource when the operation begins:

CancellationTokenSource m_cancelTokenSource = null;

private async void button_Click(object sender, EventArgs e)
{
  m_cancelTokenSource = new CancellationTokenSource();

But we pass a cancel token to our method:

await SlowProcess(prog, m_cancelTokenSource.Token);

Note that we didn’t have to create a CancellationToken, because the CancellationTokenSource created one for us. The “Source” is the source of a cancellation request, while the “Token” is something that the code in the thread can check to see if cancellation has been requested. To signal that the operation should be cancelled, you can just call the appropriate method on the source:

m_cancelTokenSource.Cancel();

However, this really doesn’t do anything other than set a flag indicating that a cancel is desired. It is up to the process itself to check to see if a cancel was requested, with code something like:

// When convenient, check for a cancel
if (ct.IsCancellationRequested)
  throw new OperationCanceledException(ct);

In fact, this code is so boiler-plate, that there is a single call on the CancellationToken to do it all in a single line:

ct.ThrowIfCancellationRequested();

To see this in place, here is the full action code we will be executing:

for (int i = 0; i < 100; i++)
{
  ct.ThrowIfCancellationRequested();
  prog.Report(i);

  Thread.Sleep(200);
}

If you never check for a cancel, then you will never cancel! Note that there are some additional useful things you can do with a CancellationToken. For example, you can set up a time limit after which, if the operation is not complete, cancel should happen automatically.

The Task

We now have progress and the ability to cancel, we’ve looked at everything except the details of the work going on. Async handling makes things extremely simple, but the SlowProcess() method is not quite just a container for the code we want to run. Instead it is a method that returns a Task object. The Task is what the await call is actually dealing with. Here is the code for SlowProcess():

private Task SlowProcess(IProgress prog, CancellationToken ct)
{
  return Task.Run(() =>
  {
    for (int i = 0; i < 100; i++)
    {
      ct.ThrowIfCancellationRequested();
      prog.Report(i);

      Thread.Sleep(200);
    }
  }, ct);
}

There is a lot going on here. First of all, note that the code that we are really running is defined as an Expression, which is passed as an argument to the Task.Run() method (That is the reason for the () => notation). This is a useful helper method that queues up work  and returns a Task. We return the Task itself from the SlowProcess() method, and the await call “awaits” on the Task. Note: we don’t really need to have the SlowProcess() method at all – we could have just put the call in place in the button_Click handler:

await Task.Run(() =>
{
  for (int i = 0; i < 100; i++)
  {
    m_cancelTokenSource.Token.ThrowIfCancellationRequested();
    ((IProgress<int>)prog).Report(i);

    Thread.Sleep(200);
  }
}, m_cancelTokenSource.Token);

This works in the same manner, but dumping it in the middle of the rest of the code makes the code harder to read and manage. If, however, you want to get access to the Task, you could change the code in button_Click to look like this:

Task t = SlowProcess(prog, m_cancelTokenSource.Token);
await t;

This makes it a little clearer as to what is going on. There are also various situations where having access to the Task is useful. For example, if you want to wait for the result of multiple tasks before moving on.

If you cared about a return value from the expression, the code would change slightly. Here is what the SlowProcess() code would look like:

private Task<int> SlowProcess(IProgress prog, CancellationToken ct)
{
  return Task<int>.Run(() =>
  {
    for (int i = 0; i < 100; i++)
    {
      ct.ThrowIfCancellationRequested();
      prog.Report(i);

      Thread.Sleep(200);
    }

    return 42;
  }, ct);
}

Note that the method now returns Task<int> instead of just Task, and there is a return statement in the Expression. Hopefully with real code, the return would actually be based on some actual process, rather than hard-coded, but you get the idea!

Our calling code would also change:

Task<int> t = SlowProcess(prog, m_cancelTokenSource.Token);
int result = await t;

And, of course, we could combine this is in a single line, as before:

int result = await SlowProcess(prog, m_cancelTokenSource.Token);

If we didn’t need access to the Task.

A note on exceptions
If you run this code in the debugger, and you click the cancel button, the debugger will stop on the line ct.ThrowIfCancellationRequested() and give you an “OperationCanceledException was unhandled by user code” popup:
Async Exception
That is because the system wants you to catch exceptions inside of the Task expression, and is warning you that you did not. However, if you do add a try/catch to the expression, then the exception will not be thrown inside of the button_Click() handler, and the only way you could tell that the operation was canceled would be by interrogating the status from the Task, which makes the code flow less well. I am told by someone at Microsoft that they are looking into ways to address this issue, but that it is extremely difficult to address without having a big impact on performance. In the meantime, you can just ignore the exception (either explicitly, or by unchecking the “Break when this exception type is user-unhandled” checkbox.

Summary

The fact that the explanation for what we have done is so much more complex than the code itself gives an idea of how powerful .NET async is. Given that most new processors are based around multiple cores, rather than raw speed, using threads will be the only way to take advantage of the machines’ power. While it has always been possible to hand-roll threading code (something I have done a lot of, sad to say) async lets you encapsulate the work without having to worry too much about the behind-the-scene details.

Just think about what we are doing in this example — we have work going on in another thread, we are not locking up the UI, and we are showing progress to the user and allowing the user to cancel the operation. Not only is the code to do this simpler than it would have been before, but it follows standard patterns that should make it easier for other developers to maintain.

You can download a solution with the example code here.

Tagged with: , , , , , , ,

I actually did a post around this topic a while ago on another site that is now defunct, but I figured it is still useful, and I have a few additional details to add.

Back in the C++/MFC days, there was a cute trick you could do in order to have a wait cursor appear while an operation was in progress, and then automatically go away. All you had to do was to create an appropriate object at the top of your method:

BOOL SomeMethod()
{
  CWaitCursor wait; 

  // Do stuff 
}

Because the wait object went out of scope at the end of the method, it could automatically restore the cursor to its old state.

You can’t do quite the same thing in C#, but you can come close–via the use of the Dispose pattern and a using statement. The code would look like this:

public void SomeMethod()
{
  using(new WaitCursor())
  {
    // Do stuff
  }
}

The using statement works with objects that implement the IDisposable interface, and is really just a shortcut. Effectively, behind the scenes, the code above will be converted into code that looks more-or-less like this:

IDisposable o = new WaitCursor();
try
{
  // Do stuff
}
finally
{
  o.Dispose();
}

This is the same pattern that it used for things like files – the Dispose() method in that case would close the file. You generally want to have files closed and resources released as soon as possible, rather than waiting for the garbage collector to get around to it at its leisure. Likewise, we want the wait cursor to show up while you are doing things, but then immediately go away.

WinForms version

There is no built-in WaitCursor class in .NET, but the code is very simple. Here is the WinForms version (comments and error checks omitted for space):

using System;
using System.Windows.Forms;

public class WaitCursor : IDisposable
{
  private Cursor m_oldCursor = null;

  public WaitCursor()
  {
    m_oldCursor = Cursor.Current;
    Cursor.Current = Cursors.WaitCursor;
  }

  public void Dispose()
  {
    Cursor.Current = m_oldCursor;
  }
}

You can now put a using(new WaitCursor()) around any code that might take a bit of time so that the user won’t try to overclick. One very common situation where it makes sense to do this is when you are bringing up dialogs:

using(new WaitCursor())
{
  using(MyDialog dlg = new MyDialog())
  {
    dlg.ShowDialog();
  }
}

You might think that this would be bad – that the wait cursor will be stuck in front of your dialog while it is being displayed, but that won’t happen at all. The wait cursor will be displayed while your dialog is being initialized, but as soon as it is actually shown, all of the processing happens in a different message loop (which processes things like drawing, clicks, etc.), and that message loop will do its own cursor handling. The wait cursor will reappear as the dialog is going away (when processing is passed back to the main message loop) and then will go away again when the code leaves the using block.

BTW – Note that I put a using statement around the dialog as well – this is a good practice, since it means that resources used by the dialog will be cleaned up immediately.

Although the using(new WaitCursor()) syntax is a little bit more verbose than just declaring an object at the top of your method, I actually have come to prefer it since you have more control (and more visibility) over the cursor’s lifetime.

WPF Version

If you are using WPF, you can do more-or-less exactly the same thing, although the code for the WaitCursor class is a bit different:

using System;
using System.Windows.Input;

public class WpfWaitCursor : IDisposable
{
  private Cursor m_oldCursor = null;

  public WpfWaitCursor()
  {
    m_oldCursor = Mouse.OverrideCursor;
    Mouse.OverrideCursor = Cursors.Wait
  }

  public void Dispose()
  {
    Mouse.OverrideCursor = m_oldCursor;
  }
}

As you can see, very similar. Although the mechanics are a little different, you can also use the WPF version around modal dialogs as well.

Longer operations

If you are doing something that may take a few moments, then showing a wait cursor is a really good idea–even if on your machine the operation is fairly fast (users might have slower machines or slower network connections, etc.). However, if you are doing anything that will take a substantial amount of time, then a wait cursor by itself is probably not going to cut it, since your UI will be locked. Eventually, Windows will show a “not responding” message in the title bar, and the user may give up on your application.

In those scenarios, you need to do work in the background and give feedback to the user. That used to be a little complicated, but since C# and .NET added really good asynchronous support, it is now quite easy. That is the topic of a future post.

Tagged with: , , ,

IMG_0713 I am somewhat known for practical jokes (and will be posting more about this eventually). However, I am not the only one in the family…

I ran an errand a couple of days ago, and while driving down the street, I checked my rear-view mirror. For a moment, I figured that I had gone a bit too far with my dieting, before realizing that my wife had decided to buckle up a skeleton in my rear seat!

 

 

Here’s a shot facing back:

IMG_0714

Tagged with:

With the recent release of C# 6.0, I thought it would be good to provide a brief explanation of the new features of the language. I’ve done them as individual posts:

There are a couple of other new features that didn’t really merit posts of their own. These primarily related to either improving handling for things (such as better resolution of overloads) or allowing some things that you probably didn’t realize you couldn’t do (such as using await in an exception catch block).

By the way – it is important to note that these are features of the C# language, independent of the .NET framework you are using. This means that you can target older versions of the framework but still take advantage of these new language features!

At some point I will also run through some of the changes and improvements in .NET 4.6 and also in Visual Studio, but those will need to wait for another day.

 

Tagged with: ,

This is one of a series of posts on some of the new features in C# 6.0, which was just released.

When Linq was added, a number of cool side-features ended up being added as well–these were things that were needed for Linq, but added value by themselves as well, such as extension methods and object initializers:

Person p = new Person() { Name = "Bob", 
    Birthday = new DateTime(2000,01,01) };

Likewise, you could also initialize collections:

List people = new List() { "Bob", "Fred", "George" };

But what you couldn’t do in this way, until now, was easily initialize a dictionary or other object that used indexers. Index initializers allow you to set values via the Indexer on an object:

Dictionary<string, int> nameToAge = new Dictionary<string, int>()
{
   ["Bob"] = 12,
   ["Fred"] = 20,
   ["George"] = 35
};

This adds some consistency to initialization, and also can be very helpful when you are using Linq and need to pass a new, but initialized, dictionary. You can also mix in initialization if your class supports an indexer along with other properties:

Person p = new Person()
{ 
  Name = "Bob", 
  Birthday = new DateTime(2000,01,01), 
  [0] = "123 Main Street" 
};

Yes, this is a terrible example. A better example would involve a dictionary-like class that also had some additional properties.

 

Here are links to posts about other new features in C# 6.0:

Tagged with: ,