Blog Archives

Google Authenticator

GoogleAuthenticator

 

As promised a while ago I am going to describe the Google Authenticator today. I do not use my own example source code this time. There is a really nice one here that I will explain. Download the source code and get some extra information from this post. This should be enough know-how to use the Google Authenticator in your own application afterwards.

What is the Google Authenticator?
The Google Authenticator is a program that allows time based passwords. It makes the online identification process much safer. You enter your Id, your password and an extra time based password. A third-party can hardly know the time based password. Even if there is a spy program on your PC that reads all your key inputs, then the hacker only has less than 30 seconds to exploit the opportunity. Otherwise he cannot use your credentials. The time component changes constantly. This is a pretty safe approach.
To steal your identity, the hacker needs to get access to the server database and decrypt your information. This is much more difficult than reading your password by using a key Trojan.

What is TOTP?

Once again our example program is using WPF.
The XAML is pretty much straight forward. Each element (TextBlock or Image) is using Binding to the underlying object. Just the Hmac TextBlock is less intuitive. The text consists of 3 TextBlocks, which in fact look like one. The green text is the second TextBlock. There is no method to write all text into one TextBlock and then color it. This would be far more complex than this 3 TextBlock solution.

 

label


property binding


type


Identity Identity string
Secret Secret string
QR code QRCodeUrl Image
Timestamp Timestamp string
Hmac HmacPart1, HmacPart2, HmacPart3 string
One-time password OneTimePassword string
Seconds to go SecondsToGo string

 

The C# source code has some hyperlinks. You should follow them in case you want to learn some detailed background information. You don’t have to do this. To apply the code in your program it should be enough to study and replicate the example source code. This code is really short and I appreciate this a lot. Many programmers make things far more complicated than needed. Are they trying to show off? I don’t know.

Let’s start from the top now.
The DispatcherTimer is the corresponding class for the good old System.Windows.Forms.Timer class. We are not using WinForms anymore. The idea behind the DispatcherTimer is that the timer fires on the Dispatcher thread. This thread is the same that your window is using. Any other thread could freeze your application.
Do not use the System.Threading.Timer class. This class is neither WPF nor WinForms related. It fires on any thread. You must not access WPF elements on arbitrary threads. On the other hand you should use the System.Threading.Timer class in case you do not want to access WPF. Don’t waste precious time of the Dispatcher thread.

The DispatcherTimer fires each 500 ms (=half second) and assigns the actual value of the 30 second countdown to the property SecondsToGo.

The properties Secret and Identity are initialized with arbitrary example data.
Then the DataContext is set. This enables the data binding between the (XAML) window and the (C#) code.

public MainWindow() {
   InitializeComponent();

   var timer = new DispatcherTimer();
   timer.Interval = TimeSpan.FromMilliseconds(500);
   timer.Tick += (s, e) => SecondsToGo = 30 - Convert.ToInt32(GetUnixTimestamp() % 30);
   timer.IsEnabled = true;

   Secret = new byte[] { 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x21, 0xDE, 0xAD, 0xBE, 0xEF };
   Identity = "user@host.com";

   DataContext = this;
}

You may have noticed already that the MainWindow class implements the interface INotifyPropertyChanged. This exposes a WPF event called PropertyChanged, which is used to notify clients via binding that a property value has changed.

namespace System.ComponentModel {
  public interface INotifyPropertyChanged {
    // Occurs when a property value changes.
    event PropertyChangedEventHandler PropertyChanged;
  }
}

You notify a client (UI) with the property name (string) rather than a delegate.
The standard WPF pattern looks like this:

public event PropertyChangedEventHandler PropertyChanged;  // INotifyPropertyChanged implementation

protected void OnPropertyChanged(string xPropertyName) {
   PropertyChangedEventHandler h = PropertyChanged;
   if (h == null) return;
   h(this, new PropertyChangedEventArgs(xPropertyName));
} //


private string _MyProperty;
public string  MyProperty { 
  get{ return _MyProperty; } 
  set { _MyProperty = value; OnPropertyChanged(“MyProperty”); } 
} //

And here is the source code from the GoogleAuthenticator example:

public event PropertyChangedEventHandler PropertyChanged;

private void OnPropertyChanged(string propertyName) {
 if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

private int _secondsToGo;
public int SecondsToGo {
   get { return _secondsToGo; }
   private set { _secondsToGo = value; OnPropertyChanged("SecondsToGo"); if (SecondsToGo == 30) CalculateOneTimePassword(); }
}

You can find that pattern many times in today’s example source code. Be aware that all properties use the same event, which is PropertyChanged. This makes your code look neat, but on the other hand you unfortunately start working with strings instead of delegates. It is part of the MVVM concept to separate code and GUI. For sure it makes debugging much more difficult and code execution slower.

Just to highlight it again. The Hmac consists of three elements. Therefore the property looks like this:

public byte[] Hmac {
  get { return _hmac; }
  private set { _hmac = value; OnPropertyChanged("Hmac"); OnPropertyChanged("HmacPart1"); OnPropertyChanged("HmacPart2"); OnPropertyChanged("HmacPart3"); }
}

What is an Hmac? To make complex interrelations easier, let’s reduce the Hmac description to “a long calculated key”, which is used to determine our time based password. Therefore to generate the key you need some kind of time input. The other component is a static password (=Secret). I added comments in the following code excerpt:

private void CalculateOneTimePassword() {
  // Get the number of seconds since 1/1/1970 and devide them by 30 seconds.
  // Thus one Timestamp unit is 30 seconds.
  Timestamp = Convert.ToInt64(GetUnixTimestamp() / 30);

  // Convert the 64 bit integer Timestamp to a byte array (8 bytes).
  // eg. ba d9 c7 02 00 00 00 00
  // Then reverse them (=> 00 00 00 00 02 c7 d9 ba) and write the result to the byte array "data".
   var data = BitConverter.GetBytes(Timestamp).Reverse().ToArray();

  // Generate the Hmac key from your password (byte array) and time (byte array).
  Hmac = new HMACSHA1(Secret).ComputeHash(data);

  // Bit-operation: Get the last 4 bits of the Hmac. The results are always equal to or between 0 and 15.
  // The offset determines the area of the Hmac that is used to generate the time based password.
  Offset = Hmac.Last() & 0x0F;

  // The Hmac is 20 bytes long. A block of 4 bytes is used for the OneTimePassword, which changes each 30 seconds.
  // 15 is the highest Offset. Therefore the last used byte is number 18 (first byte is zero based).
  // The 19th (=last) byte is the Offset. More precisely the <a href="http://en.wikipedia.org/wiki/Nibble" title="Wiki Nibble Byte" target="_blank">right nibble</a> of the 19th byte is the Offset value.
  // Bit masks are applied on the selected Hmac block to limit the number. The resulting bits are rotated to the left and added together.
  // Basically we are looking at a manual "bit to integer" conversion.
  // the result is then devided by 1,000,000 and only the remainder is taken. Consequently all results are less than 1,000,000.
  // (The bit mask 0xff is useless. I guess it was used to emphasize the technique for readability purposes. 0x7f does make sense.)
  OneTimePassword = (
         ((Hmac[Offset + 0] & 0x7f) << 24) |
         ((Hmac[Offset + 1] & 0xff) << 16) |
         ((Hmac[Offset + 2] & 0xff) << 8) |
         (Hmac[Offset + 3] & 0xff)) % 1000000;
}

When I looked at the program I was trying to find the bitmap for the QR code. You would expect a method somewhere to convert bytes to an image. But this is not the case.
The GetQRCodeUrl method generates a Url. Follow this Url and you will see that it opens an image in your browser. Google does the work for you.
The programmer of that example code has also added the Url to the description on how to generate such QR code Url. Well done! My advice is to have a quick look at it.

private string GetQRCodeUrl() {
  // https://code.google.com/p/google-authenticator/wiki/KeyUriFormat
  var base32Secret = Base32.Encode(Secret);
  return String.Format("https://www.google.com/chart?chs=200x200&chld=M|0&cht=qr&chl=otpauth://totp/{0}%3Fsecret%3D{1}", Identity, base32Secret);
}

Now we have all bits and pieces to use the Google Authenticator. But how?

1) Ask for a user identification and a password. For instance user “super@man.com” and password “Strong5rThan$trong!”.
2) Convert the password to a byte array.
3) Generate the QR code.
4) The user can scan this QR code with his android cell phone. Press “Set up account” followed by “Scan a barcode” in the Google Authenticator app.
5) The new account appears and updates in the Authenticator app. The Identity and Secret were encoded in the QR code. This is why the app knows your name already.
 
Android
 
6) From now on you can ask for the Id, the password and the time based password.
7) Make sure to have a plan B in place. The user might lose access to his Google Authenticator app. You have to provide a new login then.

Btw. I do know some people, who do not lock their tablet PC or cell phone. The Google Authenticator obviously is not for these kind of people. The problem is not behind the screen … it is in front of the screen.

migration C#, Java, C++ (day 11), future and promise

There is hardly anything directly to compare with in C#. Future and promise are C++ concepts, which are probably best compared to C# task concepts. The comparison was not easy today. Have a look at the outcome.

Wiki

future and promise

using System;
using System.Threading;
using System.Threading.Tasks;

namespace Program {
    public class Day11 {

        private class Params {
            public int Input;
            public int Result;
        }

        private void DoSomething() {
            Console.WriteLine("DoSomething()");
            Thread.Sleep(4000);
        }  //     

        private void Method1(object xObject) {
            Params lParams = xObject as Params;
            Console.WriteLine("Method1");
            Thread.Sleep(2000);
            lParams.Result = 2 * lParams.Input;
        } //

        private int Method2(int xInt1) {
            Console.WriteLine("Method2");
            Thread.Sleep(2000);
            return 2 * xInt1;
        } //

        private async Task<int> Method3(int xInt1) {
            await Task.Delay(0);
            Console.WriteLine("Method3");
            return 2 * xInt1;
        } //

        private void Method4(Params xParams, AutoResetEvent xEvent) {
            Console.WriteLine("Method4");
            Thread.Sleep(2000);
            xEvent.WaitOne();
            xParams.Result = 2 * xParams.Input;
        } //


        static void Main(string[] args) {
            Day11 lDay10 = new Day11();
            lDay10.test();
        } //

        public async void test() {
            int i;

            // use a thread to get an asynchronous result
            ParameterizedThreadStart lParams = new ParameterizedThreadStart(Method1);
            Thread thread1 = new Thread(lParams);
            Params p = new Params() { Input = 123 };
            thread1.Start(p);
            Console.WriteLine("Method1.join()");
            thread1.Join();
            Console.WriteLine("Method1 result is: " + p.Result);

            Func<int, int> t1 = new Func<int, int>(x => { return Method2(x); });
            i = t1(123); // synchronous
            IAsyncResult lResult = t1.BeginInvoke(123, null, null); // asynchronously
            lResult.AsyncWaitHandle.WaitOne();

            i = await Method3(123);
            Console.WriteLine("Method3 result is: " + i);

            p.Input = 123;
            p.Result = 0;
            AutoResetEvent lEvent = new AutoResetEvent(false);
            Task t2 = new Task(() => Method4(p, lEvent));
            t2.Start();
            lEvent.Set();
            t2.Wait();
            Console.WriteLine("Method4 result is: " + p.Result);

            Console.ReadLine();
        } //

    } // class
} // namespace

example output:
Method1.join()
Method1
Method1 result is: 246
Method2
Method2
Method3
Method3 result is: 246
Method4
Method4 result is: 246

#include <future>
#include <iostream>
#include <thread>

using namespace std;

void DoSomething() {
  cout << "DoSomething()" << endl;
  this_thread::sleep_for(chrono::seconds(4));
}  //

void Thread1(int xInt1, int &xInt2) {
  cout << "Thread1" << endl;
  this_thread::sleep_for(chrono::seconds(2));
  xInt2 = 2 * xInt1;
} //

int Thread2(int xInt1) {
  cout << "Thread2" << endl;
  this_thread::sleep_for(chrono::seconds(2));
  return 2 * xInt1;
} //

int Thread3(future<int> &xInt1) {
  cout << "Thread3" << endl;
  this_thread::sleep_for(chrono::seconds(2));
  return 2 * xInt1.get(); // .get() => waits until the promise is fullfilled
} //

int Thread4(shared_future<int> xInt1) {
  cout << "Thread4" << endl;
  this_thread::sleep_for(chrono::seconds(2));
  return 2 * xInt1.get(); // returns the same value to all waiting futures
} //

void test(){
  int i;

  // use a thread to get an asynchronous result
  thread t1(Thread1, 123, ref(i));
  cout << "Thread1.join()" << endl;
  t1.join();
  cout << "Thread1 result is: " << i << endl;

  // like a task, may be synchronous or asychronous  
  future<int> f1 = async(Thread2, 123);
  cout << "Thread2, f1.get()" << endl;
  i = f1.get(); // waits

  // like a synchronous task, which is running on the same thread
  // will be called when you get the value
  future<int> f2 = async(launch::deferred, Thread2, 123); 
  cout << "Thread2, f2.get()" << endl; 
  i = f2.get(); // waits
  cout << "Thread2 deferred result is: " << i << endl;

  // like an asynchronous task, which is running on a new thread
  future<int> f3 = async(launch::async, Thread2, 123); 
  cout << "Thread2, f3.get()" << endl; 
  i = f3.get(); // waits
  cout << "Thread2 async result is: " << i << endl;

  // same as f1, because this is the default value; the system decides what to do
  future<int> f4 = async(launch::async | launch::deferred, Thread2, 123);
  i = f4.get(); // waits

  promise<int> lPromise5; // promise to provide a value at a later time  
  future<int> f5 = lPromise5.get_future();
  future<int> f5b = async(launch::async, Thread3, ref(f5));
  DoSomething();
  cout << "lPromise5.set_value()" << endl;
  lPromise5.set_value(123); // fulfill our promise now
  cout << "f5b async result is: " << f5b.get() << endl;

  promise<int> lPromise6; // promise to provide a value at a later time
  future<int> f6 = lPromise6.get_future();
  DoSomething();
  // tell the parallel thread to stop waiting for the promise fulfillment
  lPromise6.set_exception(make_exception_ptr(runtime_error("sorry, I cannot fulfill my promise")));  

  //
  // SOME PRACTICAL ISSUES
  //
  promise<int> lPromise7; // promise to provide a value at a later time
  future<int> f7 = lPromise7.get_future();
  promise<int> lPromise8 = move(lPromise7); // you cannot assign a promise, you have to move it
  future<int> f8 = move(f7); // same with the future    

  // you cannot call future.get() more than once
  // to allow multiple consumers use:
  shared_future<int> f9 = f8.share();
  future<int> f10 = async(launch::async, Thread4, f9);
  future<int> f11 = async(launch::async, Thread4, f9);
  future<int> f12 = async(launch::async, Thread4, f9);
  future<int> f13 = async(launch::async, Thread4, f9);
  lPromise8.set_value(123);
  cout << "f10: " << f10.get() << ", f11:" << f11.get() << ", f12:" << f12.get() << ", f13:" << f13.get() << endl;

  // packaged_task
  auto t2 = bind(Thread2, 123);
  t2(); // synchronous

  packaged_task<int()> t3(bind(Thread2, 123)); // wrapper to make async calls
  t3(); // call the task  in a different context
  future<int> f14 = t3.get_future(); // getting a future is not possible with t2 
  int x = f14.get();
  cout << "f14: " << x << endl;

  cin.get();
} //

example output:
Thread1.join()
Thread1

Thread1 result is: 246
Thread2, f1.get()
Thread2

Thread2, f2.get()
Thread2
Thread2 deferred result is: 246
Thread2, f3.get()
Thread2

Thread2 async result is: 246
Thread2
DoSomething()
Thread3

lPromise5.set_value()
f5b async result is: 246
DoSomething()
Thread4
Thread4

Thread4
Thread4
f10: 246, f11:246, f12:246, f13:246
Thread2
Thread2
f14: 246

package Program;

import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Day11 {

  private static void Sleep(int xMilliseconds) {
    try {
      Thread.sleep(xMilliseconds);
    } catch (InterruptedException ex) {
      System.err.println(ex.getMessage());
    }
  } //

  private class Thread1 extends Thread {

    public int Input;
    public int Result;

    @Override
    public void run() {
      System.out.println("Thread1");
      Sleep(2000);
      Result = 2 * Input;
    } //
  } // class

  private class Thread2 {

    private final ExecutorService pool = Executors.newFixedThreadPool(5);

    public Future<Integer> getPromise(final int xInt1) {
      return pool.submit(() -> {
        System.out.println("Thread2");
        Sleep(2000);
        return 2 * xInt1;
      });
    } //
  } // class

  private class Thread3 implements Callable<Integer> {

    private final ExecutorService _Pool = Executors.newFixedThreadPool(5);
    private int _Int1;

    public Future<Integer> getPromise(final int xInt1) {
      _Int1 = xInt1;
      return _Pool.submit(this);
    } //

    @Override
    public Integer call() throws Exception {
      synchronized (this) {
        this.wait();
      }
      System.out.println("Thread3");
      Sleep(2000);
      return 2 * _Int1;
    } //
  } // class

  public final void test() throws InterruptedException, ExecutionException {

    // use a thread to get an asynchronous result    
    Thread1 t1 = new Thread1();
    t1.Input = 123;
    t1.start();
    System.out.println("Thread1.join()");
    t1.join();
    System.out.println("Thread1 result is: " + t1.Result);

    // like a task, may be synchronous or asychronous 
    Thread2 t2 = new Thread2();
    Future<Integer> f1 = t2.getPromise(123);
    System.out.println("Thread2, f1.getPromise(123)");
    int i = f1.get(); // waits   
    System.out.println("f1 result is: " + i);

    // deferred
    Thread3 t3 = new Thread3();
    Future<Integer> f2 = t3.getPromise(123);
    synchronized (t3) {
      t3.notify(); // start calculation manually    
    }
    System.out.println("Thread3 result is: " + f2.get()); // wait

    new Scanner(System.in).nextLine();
  } //

  public static void main(String[] args) throws InterruptedException, ExecutionException {
    Day11 lDay11 = new Day11();
    lDay11.test();
  } //

} // class

example output:
Thread1
Thread1.join()
Thread1 result is: 246
Thread2
Thread2, f1.getPromise(123)
f1 result is: 246
Thread3
Thread3 result is: 246

C# to C++ (advanced), review of day 4, locks and operators

As promised I am going to explain the C# side of post C# to C++ (day 4) today.
Let’s start with a dummy method. We will need it in the examples to fill in arbitrary code at the right places.

public void DoSomething() {
   Console.WriteLine("Good night my dear thread " + Thread.CurrentThread.ManagedThreadId);
   Thread.Sleep(2000);
} //

Lock

This is the standard. The Lock keyword is used frequently. The syntax is simple and locks are easy to deal with. My speed tests also tell that the speed impact of locks is negligible. Thus you can use locks without hesitation when needed.

object lAnyObject2 = new object();
public void LockUsage() {
   lock (lAnyObject2) {
      DoSomething();
   }
} //

Monitor

Locks are like macros that use the more complex Monitor class, which has more specific methods. If you don’t use the complexity of the Monitor class, then you are better of by simply using locks, which provide much better code legibility. Microsoft describes it like this:
“The functionality provided by the Enter and Exit methods is identical to that provided by the C# lock statement, except that lock wraps the Enter(Object, Boolean) method overload and the Exit method in a try…finally block to ensure that the monitor is released.”

object lAnyObject1 = new object();
public void MonitorUsage() {
   bool lLocked = false;
   try {
      Monitor.Enter(lAnyObject1, ref lLocked);  // using System.Threading;
      DoSomething();
   }
   finally {
      if (lLocked) Monitor.Exit(lAnyObject1);
   }
} //

Semaphore

Semaphores are used to limit the number of threads that can access resources. Let’s say you want to limit the output of a loudspeaker, because you cannot listen to five different sounds simultaneously. Nevertheless you want to hear urgent incoming chat message sounds from your friends while listening to nice background sounds of a game. In that case you could limit the number of threads using a resource to two. Or you are writing to a hard disk, which can deal with some simultaneous write operations. Still you want to limit the number of threads writing at the same time.
There is a slim class of Semaphores as well. SemaphoreSlim provides a lightweight semaphore class that doesn’t use Windows kernel semaphores.

private static Semaphore _Semaphore = new Semaphore(3, 3); // three objects allowed to access concurrently
public void SemaphoreUsage() {
   bool lLocked = false;
   try {
      lLocked = _Semaphore.WaitOne();
      DoSomething();
   }
   finally {
      if (lLocked) _Semaphore.Release();
   }
} //

Mutex

Mutexes are used across the system. They are identified by strings. Make sure you use unique strings to avoid conflicts. Let’s say you are running an application, which sets a Mutex. By mistake the user tries to start the same application again. But you can check the Mutex now and close/not start the second application.

private const string cMutexName = "MyMutex"
private static Mutex _Mutex = new Mutex(false, cMutexName);  // known by every process
public void MutexUsage() {
   bool lLocked = false;

   try {
      // optional complexity: access rights
      //bool lNewCreation;
      //MutexSecurity lSecurity = new MutexSecurity();
      //SecurityIdentifier lId = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
      //MutexRights lRights = MutexRights.Synchronize | MutexRights.Modify;
      //lSecurity.AddAccessRule(new MutexAccessRule(lId, lRights, AccessControlType.Allow));
      //_Mutex = new Mutex(false, cMutexName, out lNewCreation, lSecurity);
      //MutexSecurity lReverse = _Mutex.GetAccessControl();

      lLocked = _Mutex.WaitOne(2000); // You can the option to set a time limit. Here 2000 milliseconds.
      if (!lLocked) {
         Console.WriteLine("Try again later. Mutex is used by another process or thread.");
      }

      DoSomething();
   }
   finally {
      if (lLocked == true) _Mutex.ReleaseMutex();
   }
} //

Operator overloading

It does look easy, but can cause complex situations. All you have to do is to declare a method as static and replace the method name by the word operator followed by the operator itself. The return value can be of any type. The parameters should have at least one type that equals the class type. The order of the parameters is important.

Let’s have a look at the example source code of post C# to C++ (day 4) again:

public class myClass {
   // this class is not thread safe
 
   int[] Values = { 1, 2, 3 };
 
   public static myClass operator +(myClass a, myClass b) {
      int n = a.Values.Length;
      myClass lNewClass = new myClass();
      for (int i = 0; i < n; i++) lNewClass.Values[i] = a.Values[i] + b.Values[i];
      return lNewClass;
   } //      
 
   public static double operator *(myClass a, myClass b) {
      int n = a.Values.Length;
      int lSum = 0;
      for (int i = 0; i < n; i++) lSum += a.Values[i] * b.Values[i];
      return lSum;
   } //
 
   public static string operator +(string a, myClass b) {
      //return ">> " + a + b + "<<";  // WRONG! causes recursion
      return ">> " + a + b.ToString() + "<<";
   } //
 
   // I will explanation this in my post on Tuesday 4 February 2014
   // uncomment this and play with it (=>hardcore C#)
   //public static string operator +(myClass a, string b) {
   //   //return ">> " + a + b + "<<";  // WRONG! causes recursion
   //   return ">> " + a + b.ToString() + "<<";
   //} //
   // becomes even more hardcore when you have two conflicting overloads
 
   public override string ToString() {
      return "Values: " + Values[0] + " " + Values[1] + " " + Values[2] + " ";
   } //
 
} // class
 
public static void test() {
   myClass a = new myClass();
   myClass b = new myClass();
   myClass c = a + b;
   double d = a * b;
   Console.WriteLine("(Sum) " + c);  // ">> (Sum) Values: 2 4 6 <<"
   Console.WriteLine("(Sum) " + c.ToString());  // "(Sum) Values: 2 4 6"
   Console.WriteLine(c + " (Sum)");  // "Values: 2 4 6  (Sum)"
   Console.WriteLine(d);  // 14
   Console.ReadLine();
} //
source code line operator called output
myClass c = a + b; public static myClass operator +(myClass a, myClass b) {…}
double d = a * b; public static double operator *(myClass a, myClass b) {…}
Console.WriteLine(“(Sum) ” + c); public static string operator +(string a, myClass b) {…} >> (Sum) Values: 2 4 6 <<
Console.WriteLine(“(Sum) ” + c.ToString()); [not part of myClass]
operator overload “+” of the string class
(Sum) Values: 2 4 6
Console.WriteLine(c + ” (Sum)”); c.ToString() is called by the string class operator overload “+” for objects Values: 2 4 6  (Sum)

You are using operator overloading quite often without noticing it. A quick example is:

DateTime x = DateTime.Now;
DateTime y = x.AddMinutes(5);
TimeSpan t = y - x;  // operator "-" is overloaded and returns a TimeSpan.

Let’s make it more difficult now.
Uncomment public static string operator +(myClass a, string b) {…}. The statement Console.WriteLine(c + ” (Sum)”) now prints “>> >> Values: 2 4 6 << (Sum)<<“.
First the operator public static string operator +(myClass a, string b) {…} is called. This operator indirectly calls another operator public static string operator +(string a, myClass b) {…}, because the code return “>> ” + a + b.ToString() + “<<"; was called, which started with a string “>> ” + a class.

Implicit

This is used to avoid explicit cast operations and convert implicitly. But more precisely we talk about User-defined conversions.

public class ClassX {
   private readonly double _Value;
   public ClassX(double xInitValue) { _Value = xInitValue; } // constructor
   public override string ToString() { return "CLASS"; }

   // cast operation: (double)ClassX;
   public static implicit operator double(ClassX xClassX) { return xClassX._Value; }
   // cast operation: (ClassX)double;
   public static implicit operator ClassX(double xDouble) { return new ClassX(xDouble); }
}

public static void test() {
   int i = 10;
   double d1 = i;          // implicit cast operation
   double d2 = (double)i;  // explicit cast operation

   ClassX c = new ClassX(99.0);
   double d3 = c;          // implicit cast operation
   double d4 = (double)c;  // explicit cast operation
   c = 1.2;

   Console.WriteLine("class or double? " + c);  // "CLASS"
   Console.ReadLine();
}

Conflicts

So what happens when you have two classes with opposing declarations? Luckily the compiler is smart enough to detect these issues. The below source code does not compile at all. The statement Console.WriteLine(a + b) causes an error message like: “The call is ambiguous between the following methods or properties: ‘…A.operator +(…A, …B)’ and ‘B.operator +(…A, …B)'”.
The next statement Console.WriteLine(b + a) is not even a real problem. We did not define any operator overloading. Thus the compiler complains “Operator ‘+’ cannot be applied to operands of type ‘…B’ and ‘…A'”

public class A {
   public static string operator +(A a, B b) { return "class A"; }
} // class
public class B {
   public static string operator +(A a, B b) { return "class B"; }
} // class

public static void test() {
	A a = new A();
	B b = new B();
	Console.WriteLine(a + b);
	Console.WriteLine(b + a);
} //

Async and await (advanced, .Net 4.5, C# 5)

The importance is in the details. It all looks easy, but follow each step carefully today.

Windows pauses threads that are waiting for I/O operations to complete (eg. internet or file access). The same threads cannot be used for other jobs in the meantime and new threads need to be created. You could use tasks to solve this specific problem. The program would start an asynchronous task to deal with an I/O operation. After a while the same task would trigger a follow-up procedure via continuation task. It requires some work to cover all code paths, but it can be done.

C# 5 has implemented new keywords to make your life easier. You can use async to mark methods for asynchronous operations, which start synchronously and then split up as soon as the program arrives at any await keyword.

The below Print() method prints the time, sequence and ThreadId. This information is useful to understand the program cycle.

private static void Print(int xStep) {
    Console.WriteLine(DateTime.Now.ToString("HH:mm:ss") + " step " + xStep + " , thread " + Thread.CurrentThread.ManagedThreadId);
} //

static async void AsyncCalls1() {
    Print(1);
    int i = await Task.Run<int>(() => {
        Print(2); Thread.Sleep(5000);
        Print(3); return 0;
    });
    Print(4);  // same thread as in step 3

    Console.ReadLine();
    // return void
} //

example output:
19:09:36 step 1 , thread 9
19:09:36 step 2 , thread 10
19:09:41 step 3 , thread 10
19:09:41 step 4 , thread 10

The above code is a warm up for us. The method AsyncCalls1() returns void. I emphasize this seemingly insignificant fact here. If you do not return void then the compiler will complain. It wants you to add async in the calling method as well. But if you do so, then it would also ask you to add async in the calling method, that called the calling method. It would be an endless game until you arrive at Main(). And there you would not know what to do, because you cannot use async in Main(). Novices can get quite frustrated with such minuscule glitch.

What is the program doing? It starts new task, which uses another thread from the thread pool. The original thread is then neglected, there is no follow-up. Now check this out: When the created task ends, the program continues with (Task.ContinueWith()) the same thread, which it was using in the task. It seems there is no context switching.

static async void AsyncCalls2() {
    Print(1); Task<int> task = AsyncCalls3();
    Print(4); int x = await task;
    Print(7); // same thread as in step 6

    Console.ReadLine();
    // return void
} //

static async Task<int> AsyncCalls3() {
    Print(2);
    int i = await Task.Run<int>(() => {
        Print(3); Thread.Sleep(5000);
        Print(5); return 0;
    });
    Print(6); return i;  // same thread as in step 5, returning an INTEGER !!!
} //

example output:
19:10:16 step 1 , thread 9
19:10:16 step 2 , thread 9
19:10:16 step 3 , thread 10
19:10:16 step 4 , thread 9
19:10:21 step 5 , thread 10
19:10:21 step 6 , thread 10
19:10:21 step 7 , thread 10

Method AsyncCalls3() has a return value, which is a Task. The task that is started inside this method returns an integer. But doesn’t Task.Run() have to return Task<int> according to its definition? It is the await that changes the behavior. It returns the integer value (0). await has been implemented to shorten code, and this is what it does. The code is more legible.

Method AsyncCalls2() calls AsyncCalls3()
and receives an integer and not a Task<int>. This is caused by the async keyword.
AsyncCalls2() itself returns void. This is the same issue as with AsyncCalls1(). However AsyncCalls3() can return a value to AsyncCalls2(), because AsyncCalls2() itself uses the async keyword in the method definition.

Check the program sequence. I marked the steps clearly to make comprehension easy. And then analyse the thread context switching. Between step 2 and 3 is a context switch operation, but not between 5, 6 and 7. This is the same behavior as in the first example code.

public static async void AsyncCalls4() {
    Print(1); string s = await AsyncCalls5();
    Print(4);

    Console.ReadLine();
    // return void
} //

// using System.Net.Http;
public static async Task<string> AsyncCalls5() {
    using (HttpClient lClient = new HttpClient()) {
        Print(2); string lResult = await lClient.GetStringAsync("http://www.microsoft.com");
        Print(3); return lResult; 
    }
} //

example output:
19:11:47 step 1 , thread 10
19:11:47 step 2 , thread 10
19:11:48 step 3 , thread 14
19:11:48 step 4 , thread 14

When searching for async and await on the web you will find the emphasis on I/O. Most example programs concentrate on this and don’t explain what is roughly going on inside the async-I/O method itself. Basically .Net async-I/O methods deal with tasks and use a similar construction to Task.ContinueWith(). This is why I concentrated on different examples that can be used in any context (even though not very meaningful examples). The internet download example is more or less a classical one. You can use await on many I/O methods. Keep in mind that AsyncCalls4() returns void and that you are not supposed to call AsyncCalls5() from the Main() method, because you would have to add async to it.

Exceptions (part 3, advanced)

For Windows Forms and WPF we have specific exceptions to deal with. Actually these are not really exceptions. They are events, which are raised whenever any unhandled exception occurs. “Unhandled” means there is nothing that catches exceptions and the entire stack did not come up with any solution. Nothing stopped the thread falling down to its lowest level, and even that level does not know what to do with the exception. You can eg. throw an exception on a button click to cause this behavior.
These events allow applications to log information about unhandled exceptions.

In Windows Forms the EventHandler is defined in System.Threading and is called ThreadExceptionEventHandler. If you do not define this event call then your application will crash when unhandled exceptions show up.

[STAThread]
static void Main() {
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.ThreadException += Application_ThreadException;
    Application.Run(new Form1());
} //

static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) {
    Exception lException = (Exception)e.Exception;
    MessageBox.Show(lException.Message);
} //

The approach in WPF is similar. We are talking in Domains. Therefore we subscribe to AppDomain.CurrentDomain.UnhandledException .

public MainWindow() {
    InitializeComponent();
    AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;            
} //

void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) {
    Exception lException = (Exception)e.ExceptionObject;
    MessageBox.Show(lException.Message + "\nIsTerminating: " + e.IsTerminating);
} //

private void button1_Click(object sender, RoutedEventArgs e) {
    throw new Exception("user exception thrown");
} //

Exiting Tasks (advanced)

In the post “exiting Threads” (https://csharphardcoreprogramming.wordpress.com/2013/12/03/exiting-threads/) we were using a parameter class to define an exitFlag (boolean) and tell a thread when to end. There is a similar boolean for tasks supported by the Microsoft Framework. The class that contains this flag is called CancellationToken.

static void ArbitraryTask1(CancellationToken xCancellationToken) {
    while (!xCancellationToken.IsCancellationRequested) {
        Console.WriteLine(DateTime.Now.ToString("HH:mm:ss"));
        Thread.Sleep(1000);
    }

    Console.WriteLine("task says good-bye!");
} //

static void CancelTask1() {
    CancellationTokenSource lCancellationTokenSource = new CancellationTokenSource();
    CancellationToken t = lCancellationTokenSource.Token;

    Task lTask = Task.Factory.StartNew(() => ArbitraryTask1(t), t);

    Thread.Sleep(5000);
    lCancellationTokenSource.Cancel();

    Thread.Sleep(1000);
} //

The program starts a task, waits 5 seconds and then cancels the task. This is straight forward.
In the next example we exit a task by throwing an exception. This is a valid solution. But in general you should avoid exceptions as much as possible. As the name says it already: It is for exceptional situations and not for general solutions. If you use exceptions and catch() blocks frequently in your code, you will definitely slow down your performance. Throwing an exception is very time-consuming.
Nevertheless the TPL is extensively using exceptions. For instance in connection with PLINQ you will actually need to throw exceptions in order to properly report back to the user.

static void ArbitraryTask2(CancellationToken xCancellationToken) {
    ArbitraryTask1(xCancellationToken);

    xCancellationToken.ThrowIfCancellationRequested();
} //

static void CancelTask2() {
    CancellationTokenSource lCancellationTokenSource = new CancellationTokenSource();
    CancellationToken t = lCancellationTokenSource.Token;

    Task lTask = Task.Factory.StartNew(() => ArbitraryTask2(t), t);

    Thread.Sleep(5000);

    try {
        lCancellationTokenSource.Cancel();
        lTask.Wait();
    }
    catch (AggregateException e) {
        Console.WriteLine("Exception message: " + e.InnerExceptions[0].Message);
    }

    Console.ReadLine();
} //

And the following is important. In fact not throwing an exception causes unexpected behavior. Unless I misunderstood something here, this seems to be a serious issue.

static void CancelTask3() {
    CancellationTokenSource lCancellationTokenSource = new CancellationTokenSource();
    CancellationToken lToken = lCancellationTokenSource.Token;

    Task lTask = Task.Factory.StartNew(() => ArbitraryTask1(lToken), lToken);
    lTask.ContinueWith((x) => { Console.WriteLine("task cancelled"); }, TaskContinuationOptions.OnlyOnCanceled);
    lTask.ContinueWith((x) => { Console.WriteLine("task completed"); }, TaskContinuationOptions.OnlyOnRanToCompletion);

    //Thread.Sleep(5000);

    lCancellationTokenSource.Cancel();

    Console.ReadLine();
} //

example output:
task cancelled

The output is exactly what we expect. But now let’s uncomment “Thread.Sleep(5000);”. Suddenly we get something this:

example output:
18:07:37
18:07:38
18:07:39
18:07:40
18:07:41
task says good-bye!
task completed

The first 6 lines are fine. But then we get “task completed”. And all we did was adding one sleep() method in the code. If you have any idea what is causing it please leave a comment.
All I can say here is that throwing an exception solves the problem.

static void CancelTask3() {
    CancellationTokenSource lCancellationTokenSource = new CancellationTokenSource();
    CancellationToken lToken = lCancellationTokenSource.Token;

    //Task lTask = Task.Factory.StartNew(() => ArbitraryTask1(lToken), lToken);  // without throwing an exception
    Task lTask = Task.Factory.StartNew(() => ArbitraryTask2(lToken), lToken);  // with throwing an exception
    lTask.ContinueWith((x) => { Console.WriteLine("task cancelled"); }, TaskContinuationOptions.OnlyOnCanceled);
    lTask.ContinueWith((x) => { Console.WriteLine("task completed"); }, TaskContinuationOptions.OnlyOnRanToCompletion);

    Thread.Sleep(5000);

    lCancellationTokenSource.Cancel();

    Console.ReadLine();
} //

output example:
18:13:30
18:13:31
18:13:32
18:13:33
18:13:34
task says good-bye!
task cancelled

You can also comment the “Thread.Sleep(5000)” out. The returned task state does not change.
Btw. the equivalent of “ThrowIfCancellationRequested()” is

  if (token.IsCancellationRequested) throw new OperationCanceledException(token);

And here is a quick example of using timeouts in case your tasks take longer than expected.

static void CancelTask4() {
    CancellationTokenSource lCancellationTokenSource = new CancellationTokenSource();
    CancellationToken t = lCancellationTokenSource.Token;

    Task lTask1 = Task.Factory.StartNew(() => ArbitraryTask1(t), t);
    Task lTask2 = Task.Factory.StartNew(() => ArbitraryTask1(t), t);

    int  i = Task.WaitAny(new Task[] { lTask1, lTask2 }, 5000);
    if (i == -1) {
        Console.WriteLine("tasks timed out");
        lCancellationTokenSource.Cancel();  // you can comment this line out to see the change in behaviour
        if (!Task.WaitAll(new Task[] { lTask1, lTask2 }, 5000)) {
            Console.WriteLine("OMG, something went wrong again!");
        }
    }

    Console.ReadLine();
} //

lock and deadlocks (basics)

The main problem of multithreading is sharing data. You cannot access the same data from two different threads at the same time unless they are both reading. Use the lock() command to deal with sharing issues. It is nearly straightforward, just make sure you don’t cause deadlocks.

static void DeadLock() {
    object A = new object();
    object B = new object();

    Task.Factory.StartNew(() => {
        lock (A) {
            Thread.Sleep(1000);
            lock (B) Console.WriteLine("locked A, then B");
        }
    });

    Task.Factory.StartNew(() => {
        lock (B) {
            lock (A) Console.WriteLine("locked B, then A");
        }
    });

    Console.ReadLine();
} //

The example shows a simplified deadlock situation. Two tasks (=threads) wait for access to resources, in this case the objects A and B. The first task blocks access to object A. In the meantime the second task blocks access to object B and then asks for access to A. But A is blocked. The next step is that the first task finishes sleeping and asks for access to B. But B was already blocked by the second task. This results in a classical deadlock situation.

The example uses tasks, you can expect each task to use another thread. But this does not have to be the case.  Don’t expect to be lucky, it won’t work in the long run. It is necessary to assume that each task equals a new thread.
A lock() on an object can be re-entered multiple times by the same thread.

To avoid deadlocks you have to make sure that locks are requested in the same order. And you should only use locks on private objects and avoid “this” as the locking object.

static void Lock() {
    object o = new object();
    bool locked = false;

    try {
        Monitor.Enter(o, ref locked);

        Console.WriteLine("bla bla bla");
        Thread.Sleep(1000); // do something
    }
    finally {
        if (locked) Monitor.Exit(o);
    }

    // equals

    lock (o) {
      Console.WriteLine("bla bla bla");
      Thread.Sleep(1000); // do something
    }

    Console.ReadLine();
} //

The lock command is a shortcut replacing the above code. It uses the Monitor class. Generally there is no reason to not use lock() even though the Monitor class offers a lot of extras.

Parallel class (basics)

The parallel class can be found in the System.Threading.Tasks namespace. It has a couple of static methods designed to execute code concurrently. It does make sense to use parallelism when your code length justifies the creation of tasks, the code does not block each other too much (eg. lock(this) {}), the processors have free capacities and the code does not have to run in a sequence. Otherwise the performance does most likely suffer.

Let’s have a look at some examples:

public static void Parallel_For() {
    Parallel.For(0, 10, i => {
        Console.WriteLine("parallel start " + i);
        Thread.Sleep(0);
        Console.WriteLine("parallel end " + i);
    });
    Console.ReadLine();
} //

example output:
parallel start 0
parallel start 1
parallel end 0
parallel start 2
parallel end 1
parallel start 3
parallel end 3
parallel start 4
parallel end 2
parallel start 5
parallel end 4
parallel start 6
parallel end 5
parallel end 6
parallel start 8
parallel start 7
parallel start 9
parallel end 9
parallel end 8
parallel end 7

public static void Parallel_ForEach() {
    int[] n = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    Parallel.ForEach(n, i => {
        Console.WriteLine("parallel start " + i);
        Thread.Sleep(0);
        Console.WriteLine("parallel end " + i);
    });
    Console.ReadLine();
} //

example output:
parallel start 0
parallel end 0
parallel start 3
parallel start 4
parallel end 4
parallel start 5
parallel start 1
parallel start 2
parallel end 3
parallel start 6
parallel end 1
parallel start 7
parallel end 2
parallel start 8
parallel end 8
parallel start 9
parallel end 9
parallel end 6
parallel end 5
parallel end 7

public static void Parallel_ForBreak() {
    ParallelLoopResult result = Parallel.For(0, 10, (i, loopstate) => {
        Console.WriteLine("parallel start " + i);
        Thread.Sleep(0);
        if (i >= 5) loopstate.Break();
        //if (i >= 3) loopstate.Stop();
        Console.WriteLine("parallel end " + i);                                
    });
    Console.WriteLine("IsCompleted: " + result.IsCompleted);
    Console.WriteLine("LowestBreakIteration: " + result.LowestBreakIteration);
    Console.ReadLine();
} //

example output:
parallel start 0
parallel end 0
parallel start 2
parallel end 2
parallel start 3
parallel start 1
parallel end 1
parallel end 3
parallel start 6
parallel end 6
parallel start 7
parallel start 4
parallel end 7
parallel end 4
parallel start 5
parallel end 5
IsCompleted: False
LowestBreakIteration: 5

The field IsCompleted returns false when the loop did not complete. And LowestBreakIteration represents the lowest iteration number from which the break statement was called. All lower iteration numbers are executed. The function does not break, the code after break will still be executed! The Break() statement can be employed in search-based algorithms where an ordering is present in the data source.

public static void Parallel_ForBreak() {
    ParallelLoopResult result = Parallel.For(0, 100, (i, loopstate) => {
        Console.WriteLine("parallel start " + i);
        Thread.Sleep(0);
        //if (i >= 5) loopstate.Break();
        if (!loopstate.IsStopped) {
            if (i >= 25) loopstate.Stop();
            Console.WriteLine("parallel end " + i);
        }
    });
    Console.WriteLine("IsCompleted: " + result.IsCompleted);
    Console.WriteLine("LowestBreakIteration: " + result.LowestBreakIteration);
    Console.ReadLine();
} //

example output:
parallel start 0
parallel start 12
parallel end 0
parallel start 1
parallel end 1
parallel start 2
parallel end 2
parallel start 3
parallel end 3
parallel start 4
parallel end 4
parallel start 5
parallel end 5
parallel start 6
parallel start 24
parallel end 24
parallel start 25
parallel end 25
parallel end 12
IsCompleted: False
LowestBreakIteration:

The Stop() statement returns null in LowestBreakIteration. The code after Stop() is still executed!

Break() completes all iterations on all threads that are prior to the current iteration on the current thread, and then exit the loop.

Stop() stops all iterations as soon as convenient.

Tasks (basics)

A task is like a small add-on for thread pools. In fact the standard task scheduler uses the same thread pool as System.Threading.ThreadPool.
Tasks do return values, threads don’t. That is the big difference. The instance of a task class can tell you if the work is completed and what the result is. As the task scheduler uses the standard thread pool, its limitations are in the range of this pool. Therefore to adjust the behaviour of tasks you have to adjust the standard thread pool (unless you use a custom thread pool or task manager). The task manager does not start additional threads when needed, instead it waits for the pool to assign the next available thread.

static void task1() {
  Task t = new Task(() =>
    Thread.Sleep(1000);
    Console.WriteLine("hello task!");
  });

  t.Start();
  t.Wait();
  Console.WriteLine("press enter to exit");
  Console.ReadLine();
}

Calling t.Wait() is equivalent to calling Thread.Join().

static void task2() {
  Task<int> t = new Task<int>(() => {
    Thread.Sleep(1000);
    Console.WriteLine("hello task!");
    return Thread.CurrentThread.ManagedThreadId;
  });
  t.Start();
  //t.Wait();
  Console.WriteLine("task result is: " + t.Result); // implicit wait
  Console.ReadLine();
}

But when you attempt to read the t.Result the current thread will wait until the result of the task is available.
Therefore t.Wait() is commented out in method task2().

Let’s add a continuation task now. This means that we wait for the first task to finish and then start another task.

static void task3() {
  Task<int> t = new Task<int>(() => {
    Thread.Sleep(5000);
    Console.WriteLine("hello task!");
    return 1;
  });
  t.Start();
  Console.WriteLine(DateTime.Now.ToString("HH:mm:ss"));
  Task<int> t2 = t.ContinueWith((i) => {
    return i.Result + 1;
  });
  Console.WriteLine(DateTime.Now.ToString("HH:mm:ss"));
  Console.WriteLine("task result is: " + t2.Result); // implicit wait
  Console.WriteLine(DateTime.Now.ToString("HH:mm:ss"));
  Console.ReadLine();
}

The output could look like:
14:33:31
14:33:31
hello task!
task result is: 2
14:33:36

The point that I am trying to make here is that the t.ContinueWith instruction does not stop the current thread. This way you can construct a chain of commands that are executed in the future. The t2.Result then implicitly waits for the first and second task to finish.

The next example demonstrates the behavior of ContinueWith when an exception is thrown during the task execution. The code is self-explanatory. Comment the “throw new Exception();” out and see what changes.

static void task4() {
  Task<int> t = new Task<int>(() => {
    throw new Exception();
    return 1;
  });

  t.Start();
  t.ContinueWith((i) => { Console.WriteLine("Task Canceled"); }, TaskContinuationOptions.OnlyOnCanceled);
  t.ContinueWith((i) => { Console.WriteLine("Task Faulted"); }, TaskContinuationOptions.OnlyOnFaulted);
  var tasks = t.ContinueWith((i) => { Console.WriteLine("Task Completion"); }, TaskContinuationOptions.OnlyOnRanToCompletion);
  tasks.Wait();
} //

So far we were creating task instances by using the “new” keyword. There is another option. You can also create a task factory. This makes repetitive task creations easier. I am also adding child tasks to speed up a little bit.

static void task5() {
  Task<int> parent = new Task<int>(() => {
    int[] results = new int[4];
    TaskFactory factory = new TaskFactory(TaskCreationOptions.AttachedToParent, TaskContinuationOptions.ExecuteSynchronously);
    factory.StartNew(() => { results[0] = 0; Thread.Sleep(1000); Console.WriteLine("executing sub task 0"); });
    factory.StartNew(() => { results[1] = 1; Thread.Sleep(500); Console.WriteLine("executing sub task 1"); });
    factory.StartNew(() => { results[2] = 2; Thread.Sleep(1000); Console.WriteLine("executing sub task 2"); });
    factory.StartNew(() => { results[3] = 3; Thread.Sleep(750); Console.WriteLine("executing sub task 3"); });
    return results;
  });

  parent.Start();
  Task t = parent.ContinueWith(x => {
    for (int i = 0; i < 4; i++) {
      Console.WriteLine("result of task " + i + " = " + parent.Result[i].ToString());
    }
  });

  t.Wait();
  Console.ReadLine();
} //

Thread Pools (basics)

When you deal with many threads you should consider thread pools. Creating threads costs some time and resources. And even worse, you cannot reuse a thread.

Thread pool threads stay alive. The purpose is to use them again. They are waiting in a queue to be assigned new jobs. You do not have to instantiate a new thread each time you have a new job. Overall it reduces the number of threads. And in fact it does not help you a lot to have 100 threads running on a four processor machine. The system might even slow down, because it performs a lot of context switching.

Thread pools can automatically manage the amount of threads.

static void hello(object o) {
  for (int i = 0; i < 1000; i++) {
    Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " line " + i + " " + o as string);
    Thread.Sleep(2);    // let's wait 2 milliseconds to get some interaction between the two threads
  }
} //

static void Main(string[] args) {
  ThreadPool.QueueUserWorkItem(hello, "SomeFunnyParameter");
  ThreadPool.QueueUserWorkItem(hello);
  Console.ReadLine();
} //