Sponsored Ad

Wednesday, October 28, 2009

Multi-threading in .NET

One of the biggest understatements I've heard in a newsgroup was made by Patricia Shanahan, in a Java newsgroup in 2001: "Multi-threaded programming requires a little care." Multi-threading is probably one of the worst aspects of the programming period, and these days almost all application programmers need to understand that to some extent. This article serves as an introduction to multi-threading and gives some tips and suggestions for how to do it safely. Warning: I am not an expert in the field, and when the real experts start discussing in detail, my head starts spinning a little. However, I tried to pay attention to those who know what they are doing, and we hope the content of this article, at least part of a multi-threading "best practices".

This article uses the type of abbreviations in C # - int for Int32 etc. I hope this makes it easier for developers of C # to read, and will not impede any other developers too. It also monitors the talks only on how the C # variable declaration to be volatile and locking.

Multi-threaded "Hello, world"

Here is practically the simplest threading example that actually shows something happening:

using System;
using System.Threading;

public class Test
{
static void Main()
{
ThreadStart job = new ThreadStart(ThreadJob);
Thread thread = new Thread(job);
thread.Start();
for (int i=0; i < 5; i++)
{
Console.WriteLine ("Main thread: {0}", i);
Thread.Sleep(1000);
}
}
static void ThreadJob()
{
for (int i=0; i < 10; i++)
{
Console.WriteLine ("Other thread: {0}", i);
Thread.Sleep(500);
}
}
}

0 comments:

Post a Comment

Sponsored Ad

Website Update

Followers