2009年11月13日 星期五

C# Thread Implementation

I will demonstrate 3 types of thread implementations in C#. They are ThreadPool.QueueUserWorkItem(), Thread, and Win32 thread.

1. ThreadPool.QueueUserWorkItem

class Program
{
static void Main(string[] args)
{
string message = "Hi";
ThreadPool.QueueUserWorkItem(DoSomething, message);
}

//The method to be used in ThreadPool.QueueUserWorkItem, must has one parameter
//with object
static void DoSomething(object stateInfo)
{
Console.WriteLine("DoSomething: stateInfo={0}", stateInfo.ToString());
}
}


2. Thread
First, create a Daemon class. This class has a constructor with values. Besides, it has a delegate callback function.

public class Daemon
{
private string title;
private int val;

private DelegateCallbackFunc callback;

public Daemon(string _title, int _val, DelegateCallbackFunc _callback)
{
title = _title;
val = _val;
callback = _callback;
}

public void DoSomething()
{
try
{
Console.WriteLine("DoSomething: _title={0}, _val={1}", title, val);
title = title + " Dude!";
val = val + 1;

//Callback
if (callback != null)
callback(title, val);
}
catch (ThreadAbortException ex)
{

}
finally
{

}

}
}

//Declare a delegate callback method
public delegate void DelegateCallbackFunc(string _title, int _val);

Second, create and start the thread.

class Program
{
static void Main(string[] args)
{
Daemon d = new Daemon("Hi", 0, new DelegateCallbackFunc(CallbackFunc));
Thread t = new Thread(new ThreadStart(d.DoSomething));
t.Start();
}

public static void CallbackFunc(string _title, int _val)
{
Console.WriteLine("CallbackFunc: _title={0}, _val={1}", _title, _val);
}
}

3. Use win32 thread
First, create a class with extern declaration.

public class Win32
{
[DllImport("kernel32.dll", SetLastError = true)]
public static extern int CreateThread(ref SECURITY_ATTRIBUTES lpThreadAttributes,
int dwStackSize, Delegate lpStartAddress, ref object lpParameter,
int dwCreationFlags, ref int lpThreadId);

[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
public int nLength;
public IntPtr lpSecurityDescriptor;
public int bInheritHandle;
}
}

public delegate void ExecuteFunc();

Second, use this Win32 class in main program.

class Program
{
static void Main(string[] args)
{
Daemon d = new Daemon("Hi", 0, new DelegateCallbackFunc(CallbackFunc));
ExecuteFunc ef = new ExecuteFunc(d.DoSomething);

Win32.SECURITY_ATTRIBUTES sa = new Win32.SECURITY_ATTRIBUTES();
object lpParameter = new object();
int lpThreadId = 0;
Win32.CreateThread(ref sa, 0, ef, ref lpParameter, 0, ref lpThreadId);
}
}


Source code is here.

沒有留言: