Multithreading with Netduino and .NET Microframework – part 1


(to part 2, part 3 or part 4)

.NET Microframework makes multithreading with Netduino easy job. Let’s have a look how.

First, we’ll use “standard” way. In our first example, we will just create and fire new thread. It will execute in parallel with main thread:

public class Program
{
	public static void Main()
	{
		Thread someThread = new Thread(SomeThreadMethod);

		// Start the thread execution
		someThread.Start();

		// Main thread code continues
		...

		// Exiting main thread will stop someThread
	}

	private static void SomeThreadMethod()
	{
		// The thread's code
		...
	}
}

In the second example, we will execute the thread and will suspend the main thread until we resume it:

public class Program
{
	private static Thread mainThread;

	public static void Main()
	{
		// Get handle to main thread
		mainThread = Thread.CurrentThread;

		Thread someThread = new Thread(SomeThreadMethod);

		// Start the thread execution
		someThread.Start();

		// Suspend main thread execution
		mainThread.Suspend();

		//Following code will be executed after main thread is resumed
		...
	}

	private static void SomeThreadMethod()
	{
		// The thread code
		...

		// Resume main thread
		mainThread.Resume();
	}
}

Thread class contains some useful properties and methods. For example, using Priority property we can control how the thread should be scheduled compare to the other threads.

The second example contains elements of thread synchronisation. Although, it is still OK to use Suspend() and Resume() for synchronising threads, it is recommended not using them. They are causing some problems, especially when things come to sharing resources between threads. .NET Microframework provides bunch of classes to help us avoid this problems. We will look on them in future articles.

(to part 2, part 3 or part 4)

Advertisements

5 comments on “Multithreading with Netduino and .NET Microframework – part 1

  1. Pingback: Georgi's blog

  2. Pingback: Multithreading with Netduino and .NET Microframework – part 2 « Georgi's blog

  3. Pingback: Multithreading with Netduino and .NET Microframework – part 3 « Georgi's blog

  4. Pingback: Multithreading with Netduino and .NET Microframework – part 4 « Georgi's blog

  5. Pingback: Netduino Robot Drummer | niltoid.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s