CSharp examples for Reflection:Method
Execute a Method Using a New Thread
using System;//from www .j a v a 2 s .co m using System.Threading; class MainClass { private static void TraceMsg(string msg) { Console.WriteLine("[{0,3}] - {1} : {2}",Thread.CurrentThread.ManagedThreadId,DateTime.Now.ToString("HH:mm:ss.ffff"), msg); } private static void DisplayMessage(object config) { ThreadStartData data = config as ThreadStartData; if (data != null) { for (int count = 0; count < data.Iterations; count++) { TraceMsg(data.Message); // Sleep for the specified period. Thread.Sleep(data.Delay); } } else { TraceMsg("Invalid thread configuration."); } } public static void Main() { Thread thread = new Thread(DisplayMessage); thread.IsBackground = false; ThreadStartData config = new ThreadStartData(5, "A thread example.", 500); TraceMsg("Starting new thread."); thread.Start(config); for (int count = 0; count < 13; count++) { TraceMsg("Main thread continuing processing..."); Thread.Sleep(200); } } } class ThreadStartData { public ThreadStartData(int iterations, string message, int delay) { this.iterations = iterations; this.message = message; this.delay = delay; } private readonly int iterations; private readonly string message; private readonly int delay; // Properties provide read-only access to initialization data. public int Iterations { get { return iterations; } } public string Message { get { return message; } } public int Delay { get { return delay; } } }