C#

Multithreading: C# vs. Java

In my pervious post I described basic multithreading constructs in C#. Now, I would like to compare them to conforming constructs in Java. It might be useful for those of you, who has already created some multithreaded applications in Java, and would like to learn how to do the same in C#.

Creating a new thread

C#:

using System;
using System.Threading;

class ThreadTest
{
  static void Main()
  {
    Thread t = new Thread (Method);
    t.Start();    
  }
 
  static void Method()
  {
    Console.WriteLine("Thread started");
  }
}

Java:

public class Program {
  public static void main(String[] args) {
    ThreadClass t = new ThreadClass();
    t.start(); 
  }
}
 
class ThreadClass extends Thread {
  @Override
  public void run() {
    System.out.println("Thread started");
  }
}

Waiting for another thread to finish

C#:

using System;
using System.Threading;

class ThreadTest
{
  static void Main()
  {
    Thread t = new Thread (Method);
    t.Start();   
    t.Join(); //wait for thread t
    Console.WriteLine("Created thread finished");
  }
 
  static void Method()
  {
    Console.WriteLine("Started new thread...");
    Thread.Sleep(1000);
    Console.WriteLine("Finishing new thread...");
  }
}

Java:

public class Program {
  public static void main(String[] args) {
    ThreadClass t = new ThreadClass();
    t.start();
    try {
      t.join(); //wait for thread t
      System.out.println("Created thread finished");
	} catch(InterruptedException e) { 
	  // handle exception
	}
    
  }
}
 
class ThreadClass extends Thread  {
  @Override
  public void run() {
    System.out.println("Started new thread...");
    try {
      Thread.sleep(1000);
    } catch(InterruptedException e) {
      // handle exception
    }
    System.out.println("Finishing new thread...");
  }
}

Accessing shared variable

C#:

using System;
using System.Threading;

class ThreadTest
{
  static readonly object locker = new object();
  static int sharedVariable;

  static void Main()
  {
    Thread t = new Thread (Method);
    t.Start();   
    lock(locker)
    {
      // sample operation
      if(sharedVariable==0)
      {
        sharedVariable = 1;
      }
    }
  }
 
  static void Method()
  {
    lock(locker)
    {
      // sample operation
      if(sharedVariable>0)
      {
        sharedVariable++;
      }
    }
  }
}

Java:

public class Program {
  public static int sharedVariable;
  public static final Object lock = new Object();
  public static void main(String[] args) {
    ThreadClass t = new ThreadClass();
    t.start(); 
    synchronized(lock)
    {
      //sample operation
      if(sharedVariable==0) {
        Program.sharedVariable = 1;
      }
    }      
  }
}
 
class ThreadClass extends Thread {
  @Override
  public void run() {
    synchronized(Program.lock) {
      //sample operation
      if(Program.sharedVariable>0) {      
        Program.sharedVariable++;
      }
    }
  }
}

Signaling

C#:

using System;
using System.Threading;

class ThreadTest
{
  static EventWaitHandle _waitHandle = new AutoResetEvent (false);
 
  static void Main()
  {
    new Thread (Waiter).Start();    
    Console.WriteLine("Wait for notification...");
    _waitHandle.WaitOne();
    Console.WriteLine("Notification received.");
  }
 
  static void Waiter()
  {
    Thread.Sleep (1000);
    Console.WriteLine("Sending notification...");
    _waitHandle.Set();
  }
}

Java:

class Program
{ 
  public static void main(String[] args) {
    ThreadClass t = new ThreadClass();
    t.start();
    System.out.println("Wait for notification..."); 
    synchronized(t) {
      try {
        t.wait();
      } catch(InterruptedException e) {
        //handle exception
      }
    }
    System.out.println("Notification received.");
  }
}
 
class ThreadClass extends Thread {
  @Override
  public void run() {
  	try {
      Thread.sleep(1000);
    } catch(InterruptedException e) {
      //handle exception
    }    
    System.out.println("Sending notification...");
    synchronized(this) {
      notify();
    }
  }
}

Summary

As we can see, threading constructs in both languages are very similar.

I put all above code in github repository: Threading-in-CSharp-vs-Java.

Do you think, there are some other fundamental examples, which should be mentioned in this post?


Multithreading in C#

Multithreading is one of the advanced topics in Computer Science. Every Developer, sooner or later will need to write some multithreaded application. It is definitely better to do it sooner, even just for exercise, than later.

Everyone who attend a University and got a CS degree had to write at least one concurrent application. Usually, in Java, as ‘standard language for Universities’. At least that was in my case, and two Universities I attended (Wroclaw University of Technology and Kansas State). Many University-based resources from Google are in Java. Sometimes there is C/C++ used. That’s my observation after googling.

As .NET Developer I was interested in multithreading in C#. One of the best sources about that is Threading in C# by Joseph Albahari. It’s an overview of all threading-related features in C#. In this post, I would like to make an overview of the most basic techniques: accessing shared resources and signaling.

Basic locking

The issues with threading are usually correlated with shared resources (e.g. variables). One thread can start modifying it, while in meantime another thread also start do that. Then, sometimes, we cannot predict the final state of the resource (value of variable). Moreover, in one execution it can be value set by thread #1 and in the other – by thread #2.

To solve this issue, we have constructs such as: semaphors or monitors. In C#, the monitor implementation is lock statement. To apply it, we need ‘locker object’, which has to be locked before access to shared resources and unlocked after. Once ‘locker object’ is locked, other threads has to wait until it becomes unlocked. Look at below example (from Albahari’s eBook):

using System;
using System.Threading;

class ThreadTest 
{
  static bool done;    // Static fields are shared between all threads
 
  static void Main()
  {
    new Thread (Go).Start();
    Go();
  }
 
  static void Go()
  {
    if (!done) { done = true; Console.WriteLine ("Done"); }
  }
}

The bool variable done is shared resource. Above program will have 2 threads. First one, starts in a new thread and second one, right after the first one, in main thread. Both will try to access shared resource. We can see that during method Go() execution, the shared variable is accessed actually 2 times. First – to check its value, and second – to set it (if it was false). The problem is that thread #1 can access it first (when it is false), then give up processor for thread #2, which also will check the value (still false) and we will get “Done” printed twice. That’s something we do not want. To solve this issue, we introduce ‘locker object’ represented by variable locker.

using System;
using System.Threading;

class ThreadSafe 
{
  static bool done;
  static readonly object locker = new object();
 
  static void Main()
  {
    new Thread (Go).Start();
    Go();
  }
 
  static void Go()
  {
    lock (locker)
    {
      if (!done) { Console.WriteLine ("Done"); done = true; }
    }
  }
}

Now, the if statement is secured by lock. Every thread, which wants to enter it, has to obtain the lock. Once one thread obtain the lock, another threads cannot. They have to wait, until it becomes unlocked. In above example, when thread #1 has the lock and start executing critical section, then even if it give up for thread #2, we have warranty that another thread will not enter the critical section. Additionally, only thread #1 can release the lock.

The following code:

lock(locker) 
{ 
    //code 
}

is equivalent to (C# 4.0):

bool lockTaken = false;
try
{
  Monitor.Enter (locker, ref lockTaken);
  //code 
}
finally { if (lockTaken) Monitor.Exit (locker); }

Signaling

Another common technique in multithreaded applications is signaling. It is notifying other thread(s). For example: thread #1 can start another thread (thread #2) and wait for signal from it (e.g. that it finished some operation). Thread #2 is performing the operation, while thread #1 is waiting. Once thread #2 finish operation, it notify (send signal) thread #1, which then can continue other computations.

In the example below, then main thread, create new thread to perform Operation. After that it performs some computation and when it is done, it waits for thread #2 to finish its operations. After main thread get notification from thread #2, it can proceed.

using System;
using System.Threading;

class BasicWaitHandle
{
  static EventWaitHandle _waitHandle = new AutoResetEvent (false);
 
  static void Main()
  {
    new Thread (Operation).Start();
    Thread.Sleep (1000);                  // Computation...
    Console.WriteLine ("Wait...");
    _waitHandle.WaitOne();                    // Wait for notification
    Console.WriteLine ("Notified!");
  }
 
  static void Operation()
  {
    Console.WriteLine ("Start operation...");
    Thread.Sleep(2000);               // Computation...
    Console.WriteLine ("Operation finished!");
    _waitHandle.Set();                // Notify the Waiter
    Thread.Sleep(1000);         // Some other computation...
  }
}

Producer-Consumer

The classic multithreaded application is Producer–consumer. Additionally, it is wide used across many real-life applications. In the listing below, there is Producer-Consumer implementation in C# (taken from Threading in C# – part 2):

using System;
using System.Threading;
using System.Collections.Generic;
 
class ProducerConsumerQueue : IDisposable
{
  EventWaitHandle _wh = new AutoResetEvent (false);
  Thread _worker;
  readonly object _locker = new object();
  Queue<string> _tasks = new Queue<string>();
 
  public ProducerConsumerQueue()
  {
    _worker = new Thread (Work);
    _worker.Start();
  }
 
  public void EnqueueTask (string task)
  {
    lock (_locker) _tasks.Enqueue (task);
    _wh.Set();
  }
 
  public void Dispose()
  {
    EnqueueTask (null);     // Signal the consumer to exit.
    _worker.Join();         // Wait for the consumer's thread to finish.
    _wh.Close();            // Release any OS resources.
  }
 
  void Work()
  {
    while (true)
    {
      string task = null;
      lock (_locker)
        if (_tasks.Count > 0)
        {
          task = _tasks.Dequeue();
          if (task == null) return;
        }
      if (task != null)
      {
        Console.WriteLine ("Performing task: " + task);
        Thread.Sleep (1000);  // simulate work...
      }
      else
        _wh.WaitOne();         // No more tasks - wait for a signal
    }
  }
}

class Program
{
	static void Main()
	{
	  using (var q = new ProducerConsumerQueue())
	  {
	    q.EnqueueTask ("Hello");
	    for (int i = 0; i < 10; i++) q.EnqueueTask ("Say " + i);
	    q.EnqueueTask ("Goodbye!");
	  }
	 
	  // Exiting the using statement calls q's Dispose method, which
	  // enqueues a null task and waits until the consumer finishes.
	}
}

It takes advantage of locking and signaling. Producer is creating tasks and putting them into the buffer. Consumer is consuming tasks (fetching them from the buffer). In above program: the buffer is implemented as Queue.

There are two threads:

  • Main thread – creating tasks and adding them into the queue (enqueuing)
  • Work thread – processing tasks (dequeuing)

‘Work thread’ is consuming tasks if the queue is not empty. If the queue is empty, instead of checking its content continuously, it waits for the signal from Main thread. The Main thread notify Work thread every time it enqueued new task into the queue. Work thread terminates, once it receive null task. In above program, it happens when we quit the using statement in Main thread. That cause Dispose() method call (in ProducerConsumerQueue class), which enqueues null task into the queue. During enqueuing and dequeuing, the queue is locked using lock construct.

More detailed description of this implementation can be found on Joe Albahari’s article.

Summary

There are many advantages of multithreading: speeding up applications by performing operations in different thread, while processor is waiting for I/O operation or making UI thread responsive all the time, while processing is done in background. However, multithreaded applications are much harder to find bugs and debug. Because of that: you should avoid multithreading everywhere when possible. Especially, when threads access the shared resource.

To get familiar with multithreading you can read Introduction to Multithreading (with examples in Java) and Multi-threading in .NET: Introduction and suggestions (with “Hello, world” example in C#).

For a jump start you may find useful a session from TechEd New Zealand 2012: Multi-threaded Programming in .NET from the ground up (it’s 2 years old, but still accurate).

To learn more about multithreading in C#, I strongly recommend you Threading in C# by Joseph Albahari, which is also part of C# 5.0 in a Nutshell (book I am reading now…and also recommending!).


My Pomidoro Windows 8 app is getting famous

Over a year ago I created simple Windows 8 app: Pomidoro (the name ‘Pomodoro’ was already taken at the Windows Store). And yes, it is for applying The Pomodoro Technique. I published it to the Windows Store on January 7, 2013.

Pomidoro screenshot

The reason I created this app, was to learn Windows 8 Metro apps development.

From time to time I receive e-mails that my app got some third party award or was reviewed by some website I have never heard about.

A few weeks ago I received e-mail from Best Windows 8 Apps. My app received Editor’s pick award:

Pomidoro Editor's pick award

A few days ago I received e-mail from AppFeds. They states, that they are tracking 116,642 apps. Windows 8 Store contains over 144,739 (source). Now, my app is 579/673 in the productivity category.

Pomidoro Windows 8 app in Ranking in Productivity

Pomidoro Windows 8 app in Top Free Ranking in Productivity

I checked how many productivity apps they have and I was a little bit surprised. They have 673 apps in category Productivity. How is this possible that my app was ranked 958 in January 31? Did they have more apps or they are just lying? First warning about credibility of their website.

EDIT (after clarification from AppFeds, see comment): They have more than 2800 apps in category Productivity and almost 700 of them are well received. My app was 958 in January, now is 674. Yesterday (before the comment from AppFeds was posted), my app was 557.

Pomidoro ranking in productivity March 12, 2014

But, in the same time, my app is in page 38, when I sort Productivity apps, by ranking (with ‘Well Received’ filter off). There is 10 apps per page, which means my app is in top 380(?) Why there is a difference between the list and above chart? Maybe guys from AppFeds can explain that as well? [End Of Edit]

Yesterday I received another e-mail. It made me to create this post. The e-mail was from I Love Free Software:

Hi jj09 team,

I am Ubaidullah from www.ilovefreesoftware.com. We recently reviewed Pomidoro on our website here:

http://www.ilovefreesoftware.com/24/featured/free-pomodoro-timer-apps-windows-8.html

We are a popular tech website and get hundreds of thousands of visitors from over 150 countries around the world.

It would be great if you could add a link to the review on your website. This would tell your visitors that we have reviewed your app as one of the best free app available (and that would add up to your credibility as well).

I have attached a badge with this mail which you can flaunt on your website, and link that to the review. Alternatively, you can just add this code:

<a href=”http://www.ilovefreesoftware.com/24/featured/free-pomodoro-timer-apps-windows-8.html” title=”Free Software” ><img border=”0″ src=”http://cdn.ilovefreesoftware.com/wp-content/uploads/2011/03/ilovefreesoftware_reviewed_5Star.png”/></a>

Feel free to get back to me with any questions.

Have Fun,

Ubaidullah Khan
Collaboration Manager

I checked this review. Doesn’t look like a simple scam. It is neither high quality review. The cool thing is my app is 1st of 4 best Pomodoro apps 🙂 This is the badge from them:

Pomidoro - I love free software reviewed 5 Star

* Of course I didn’t paste link provided by them. The picture is stored on my server for security reasons.

Is that means my tiny app is good? Maybe average Windows Store apps are not very high quality (if app created within one day can be better than them)? Or maybe there are people who trying to get their websites popular, by scaming Windows Apps’s creators? I think the last reason is the most likely 🙂

Now, let’s look at the most accurate statistics – Windows Store:

Pomidoro Windows Store stats

The problem here is following: how can I check how good my app is? The best way to do that is compare it with other apps. But how? I was trying to find some Apps rankings on Windows Store websites and I didn’t find any. Maybe I am not good google user. I found some ranking on Microsoft Store for Windows Phone (using Bing), but not for Windows 8.

I know, I am feeding scammers by linking these third party websites here. On the other had, some of them (e.g. this or that) have better UX than Windows Store websites. I spent 10 minutes trying to find Windows Store Apps rankings online and I failed. I know you can sort Apps in Windows Store by popularity, but why it is not available online? In the same time, third party websites like AppFeds have pretty nice and clear UX for Apps Catalogs. Their data may be not accurate, but the UI is nice. Maybe guys from Microsoft should think about something like that?


The Story of dotNetConfPL

It is all about people and cooperation!

Long story short

April 25-26 – dotNetConf took place, online conference for .NET developers, organized by Scott Hanselman and Javier Lozano

April 27 – I text Pawel Sawicz, that we can organize something similar with Polish speakers and name it dotNetConfPL, he said: “it’s a good idea”. (motivation++)

April 28 – Pawel told me that Michal Franc is also interested and we created google doc to write down ideas and todos. (motivation++)

May 24 – We ask Scott Hanselman whether we can use dotNetConfPL as a name of the conference (because it’s very similar to name of his conference). He and Javier Lozano confirmed in the same day and wished us good luck. (motivation++)

June 6 – We sent e-mail to Maciej Aniserowicz, with a proposition to be a speaker at our conference.

June 7 – He responded: yes (we had first speaker!). (motivation++)

After that, we were inviting rest of speakers and most of them accepted our invitations. We really appreciate this, because they didn’t get any benefits from that.

July 14 – We announced dotNetConfPL on facebook and gain almost 50 registrations for the event within 1 hour! (motivation++)

The week of the conference

A few days before the conference we did initial testing with speakers. To check, whether their microphone, resolution, etc. is set properly. Sometimes we had issues with Google Hangouts. Solution for that was simply disconnect and create a new ‘hangout’. Our initial plan was to make only 1 hangout for entire conference, because each one has different link. We wanted to avoid forcing people to refresh the website or use of SignalR. However after that, we decided it will be better (safer and more flexible) to create separate ‘hangouts’ for each speaker and update link using SignalR.

Website for conference was created in ASP.NET MVC framework. The SignalR+CounchDB feature was implemented day before conference. After the conference I found interesting file in our solution:

dotnetconfpl - code

It is worth to mention that during the conference I was in Manhattan, KS, while Pawel and Michal were in Wroclaw, Poland. The image below, is my Command Center. ThinkPad X220 is connected with 2 monitors and through it I am connected to speakers. On MacBook I am connected via Skype with Michal and Pawel. On Surface I have live streaming (about 30 seconds delay) to be sure everything is working fine. The only issue I had, was not enough ears. I had only two: in one I was connected to the speaker, second – Michal and Pawel, and if I had third, I would be able to track the live streaming 🙂

dotNetConfPL - center

Sessions

All sessions were in Polish. If you don’t speak Polish, you can mute the sound, play this in background and watch 🙂 You won’t get full experience, but still can get a lot from each session!

What is cool, all of them are for beginners and non-beginners in the same time. Which means, everybody will learn something from each session. Additionally: all of them are in HD (720p). Google enabled it by the end of August.

Maciej Aniserowicz: Unit testing in .NET

Maciej shows TDD live example. From nothing to well-tested communication with external API.

Filip Wojcieszyn: scriptcs – C# on diet

Filip shows how to use C# in Console and/or in SublimeText.

Jakub Gutkowski: JavaScript for C# developer

Jakub shows differences between C# and JavaScript, and language flavors every developer should be aware of, which may cause hard to track bugs.

Tomasz Janczuk: Node.js, Edge.js and Windows Azure

This session blew my mind (and not only mine). Edge.js allows you to mix Node.js, C#, F#, IronPython, PowerShell and T-SQL code in one file!

Maciej Grabek: Windows Phone 8 Tips & Tricks

Maciej shows set of useful(8) tricks for WP8 developers. From displaying helper-grid during development, to how to get more ratings for your app.

Summary

Everything went well. We didn’t have any problems with streaming (thanks Google Hangouts) and website (thanks Windows Azure and SignalR). I noticed that sometimes, on my Surface RT, IE11 wasn’t refreshing the link. But, come on…it’s IE, so we can ignore it 🙂

We had room on JabbR for discussion and ask questions to speakers. For a few minutes, even David Fowler (one of SignalR developers) visited it.

I am very glad that many people attended the conference. We had more than 600 registrations, almost 100 people in JabbR room and around 100-200 online viewers. But many people were watching the conference together, and in this case 1 online viewer = more that 1 physical viewers.

dotNetConfPL - atCompany
dotNetConfPL - pizza

Thank you very much for all speakers! You did a great job guys, all sessions are international level!
Thanks to Michal and Pawel for organizing this conference with me.
Thanks to Scott Hanselman and Javier Lozano for inspiration.
And…thank you very much for all of you who were watching the conference and spreading the news!

EDIT:
Short list of tools/technologies we were using for the conference:

  • Google Hangouts
  • ASP.NET MVC
  • SignalR
  • CouchDB
  • Windows Azure (to be able to scale the instance, depends on the number of users)
  • Google Docs (as a database for most important information)
  • Trello (for tasks management)
  • AppHarbor (as test server)

dotNetConfPL – online conference for .NET developers

Together with Michal Franc and Pawel Sawicz we are organizing online conference for .NET Developers: dotNetConfPL. It will take place on October 12 (3pm-10pm UTC+2), on the Internet! We have many great speakers and hot sessions.

Attendees will be able to ask questions through dotNetConfPL2013 room on JabbR.

Today, we have over 500 registered users! Additionally, during the conference we will give away 6 ReSharper licenses (thank you JetBrains).

Registration is not obligatory, but only registered users will have chance to win ReSharper licenses.

See you there!