Saturday, January 10, 2009

How to use Multithreading in C# Console Application

C# Multithreading Example – Continuous Alert

A query from our good blog friend SnakyJake led me to code a small multithreading stuff. The following example will torment the user with beeps till he/she inputs some value.

First let us create a small class that will handle the beeps

public class ClassBeep

{

private volatile bool EnoughBeeping;

public void StartBeeping()

{

while (!EnoughBeeping)

{

Console.Beep();

}

}

public void StopBeeping()

{

EnoughBeeping = true;

}

}

ClassBeep has two public methods, one to start beeping (and continuing) with it and another to stop the beep.

We also have a volatile variable EnoughBeeping which sets/resets the Beeps

This is quite simple. Isn’t it.

The next step is to code the main function to get the user input.

Wait a minute … here are the directives

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading;

The last one “System.Threading” is the one we have added to the default directives.

Let us create an object for our Beep class

ClassBeep CBeep = new ClassBeep();

and create a thread and attach the function to it

Thread CBeepThread = new Thread(CBeep.StartBeeping);

We can now start the additional thread (worker thread)

CBeepThread.Start();

while (!CBeepThread.IsAlive) ;

Beep starts …

Now we can provide some instructions to the main thread

Thread.Sleep(1);

Console.WriteLine("Please enter the name");

string sText = Console.ReadLine();

int iLen = 0;

iLen = sText.Length;

while (iLen == 0)

{

sText = Console.ReadLine();

iLen = sText.Length;

}

The above loop will be executed till the user inputs a value.

Once the execution comes out of the loop, let us stop the beep and join the worker thread with the main one

CBeep.StopBeeping();

CBeepThread.Join();

Here is the full code of the main module

static void Main(string[] args)

{

ClassBeep CBeep = new ClassBeep();

Thread CBeepThread = new Thread(CBeep.StartBeeping);

CBeepThread.Start();

while (!CBeepThread.IsAlive) ;

Thread.Sleep(1);

Console.WriteLine("Please enter the name");

string sText = Console.ReadLine();

int iLen = 0;

iLen = sText.Length;

while (iLen == 0)

{

sText = Console.ReadLine();

iLen = sText.Length;

}

CBeep.StopBeeping();

CBeepThread.Join();

Console.WriteLine("Welcome {0}", sText);

}

Try it out. You can try overload of Beep Function to make your user have soothing and rhyming beeps as background.

Hope you get things done through beepsJ

1 comment: