Csharp/CSharp Tutorial/Thread/Thread Creation
Содержание
- 1 Adding with Thread objects
- 2 Communicating Data to a Thread
- 3 Create a thread of execution
- 4 Create multiple threads of execution
- 5 List threads for PID
- 6 Passing an argument to the thread method.
- 7 Primary Thread statistcs
- 8 Starting a Method in a Separate Thread
- 9 The creation of threads
- 10 Thread method with no parameter
- 11 Thread method with parameter
- 12 Thread Stats
- 13 Use anonymous delegate as the worker method to create Thread
Adding with Thread objects
<source lang="csharp">using System; using System.Collections.Generic; using System.Text; using System.Threading; class AddParams {
public int a; public int b; public AddParams(int numb1, int numb2) { a = numb1; b = numb2; }
} class Program {
public static void Add(object data) { if (data is AddParams) { Console.WriteLine("ID of thread in Add(): {0}",Thread.CurrentThread.GetHashCode()); AddParams ap = (AddParams)data; Console.WriteLine("{0} + {1} is {2}", ap.a, ap.b, ap.a + ap.b); } } static void Main(string[] args) { Console.WriteLine("ID of thread in Main(): {0}", Thread.CurrentThread.GetHashCode()); AddParams ap = new AddParams(10, 10); Thread t = new Thread(new ParameterizedThreadStart(Add)); t.Start(ap); Console.ReadLine(); }
}</source>
Communicating Data to a Thread
<source lang="csharp">using System; using System.Threading;
class Sum {
public Sum(int op1, int op2) { Console.WriteLine("[Sum.Sum] Instantiated with values of {0} and {1}", op1, op2); this.op1 = op1; this.op2 = op2; } int op1; int op2; int result; public int Result{ get { return result; } } public void Add() { Thread.Sleep(5000); result = op1 + op2; }
}
class ThreadData {
static void Main() { Sum sum = new Sum(6, 42); Thread thread = new Thread(new ThreadStart(sum.Add)); thread.Start(); for (int i = 0; i < 10; i++) { Thread.Sleep(200); Console.Write("."); } thread.Join(); Console.WriteLine("[Main] The result is {0}", sum.Result); Console.ReadLine(); }
}</source>
Create a thread of execution
<source lang="csharp">using System; using System.Threading;
class MyThread {
public int count; string thrdName; public MyThread(string name) { count = 0; thrdName = name; } // Entry point of thread. public void run() { Console.WriteLine(thrdName + " starting."); do { Thread.Sleep(500); Console.WriteLine("In " + thrdName + ", count is " + count); count++; } while(count < 10); Console.WriteLine(thrdName + " terminating."); }
}
class MainClass {
public static void Main() { Console.WriteLine("Main thread starting."); MyThread mt = new MyThread("Child #1"); Thread newThrd = new Thread(new ThreadStart(mt.run)); newThrd.Start(); do { Console.Write("."); Thread.Sleep(100); } while (mt.count != 10); Console.WriteLine("Main thread ending."); }
}</source>
Main thread starting. Child #1 starting. .....In Child #1, count is 0 .....In Child #1, count is 1 ....In Child #1, count is 2 .....In Child #1, count is 3 ....In Child #1, count is 4 .....In Child #1, count is 5 .....In Child #1, count is 6 ....In Child #1, count is 7 .....In Child #1, count is 8 ....In Child #1, count is 9 Child #1 terminating. Main thread ending.
Create multiple threads of execution
<source lang="csharp">using System; using System.Threading;
class MyThread {
public int count; public Thread thrd; public MyThread(string name) { count = 0; thrd = new Thread(this.run); thrd.Name = name; thrd.Start(); } void run() { Console.WriteLine(thrd.Name + " starting."); do { Thread.Sleep(500); Console.WriteLine("In " + thrd.Name + ", count is " + count); count++; } while(count < 10); Console.WriteLine(thrd.Name + " terminating."); }
}
class MainClass {
public static void Main() { Console.WriteLine("Main thread starting."); MyThread mt1 = new MyThread("Child #1"); MyThread mt2 = new MyThread("Child #2"); MyThread mt3 = new MyThread("Child #3"); Thread.Sleep(10000); Console.WriteLine("Main thread ending."); }
}</source>
Main thread starting. Child #1 starting. Child #2 starting. Child #3 starting. In Child #1, count is 0 In Child #2, count is 0 In Child #3, count is 0 In Child #1, count is 1 In Child #2, count is 1 In Child #3, count is 1 In Child #1, count is 2 In Child #2, count is 2 In Child #3, count is 2 In Child #1, count is 3 In Child #2, count is 3 In Child #3, count is 3 In Child #1, count is 4 In Child #2, count is 4 In Child #3, count is 4 In Child #1, count is 5 In Child #2, count is 5 In Child #3, count is 5 In Child #2, count is 6 In Child #1, count is 6 In Child #3, count is 6 In Child #2, count is 7 In Child #1, count is 7 In Child #3, count is 7 In Child #2, count is 8 In Child #1, count is 8 In Child #3, count is 8 In Child #2, count is 9 Child #2 terminating. In Child #1, count is 9 Child #1 terminating. In Child #3, count is 9 Child #3 terminating. ^CTerminate batch job (Y/N)? n
List threads for PID
<source lang="csharp">using System; using System.Collections.Generic; using System.Text; using System.Diagnostics;
class Program { static void Main(string[] args) { Process theProc = null; try { theProc = Process.GetProcessById(12344); } catch { Console.WriteLine("-> Sorry...bad PID!"); return; } Console.WriteLine("Here are the threads used by: {0}",theProc.ProcessName); ProcessThreadCollection theThreads = theProc.Threads; foreach (ProcessThread pt in theThreads) { string info = string.Format("-> Thread ID: {0}\tStart Time {1}\tPriority {2}",pt.Id, pt.StartTime.ToShortTimeString(), pt.PriorityLevel); Console.WriteLine(info); } } }</source>
Passing an argument to the thread method.
<source lang="csharp">using System; using System.Threading;
class MyThread {
public int count; public Thread thrd; public MyThread(string name, int num) { count = 0; thrd = new Thread(new ParameterizedThreadStart(this.run)); thrd.Name = name; thrd.Start(num); } void run(object num) { Console.WriteLine(thrd.Name + " starting with count of " + num); do { Thread.Sleep(500); Console.WriteLine("In " + thrd.Name + ", count is " + count); count++; } while(count < (int) num); Console.WriteLine(thrd.Name + " terminating."); }
}
class MainClass {
public static void Main() { MyThread mt = new MyThread("Child #1", 5); MyThread mt2 = new MyThread("Child #1", 3); do { Thread.Sleep(100); } while (mt.thrd.IsAlive | mt2.thrd.IsAlive); Console.WriteLine("Main thread ending."); }
}</source>
Child #1 starting with count of 5 Child #1 starting with count of 3 In Child #1, count is 0 In Child #1, count is 0 In Child #1, count is 1 In Child #1, count is 1 In Child #1, count is 2 In Child #1, count is 2 Child #1 terminating. In Child #1, count is 3 In Child #1, count is 4 Child #1 terminating. Main thread ending.
Primary Thread statistcs
<source lang="csharp">using System; using System.Threading; class Program {
static void Main(string[] args) { Thread primaryThread = Thread.CurrentThread; primaryThread.Name = "ThePrimaryThread"; Console.WriteLine("Name of current AppDomain: {0}", Thread.GetDomain().FriendlyName); Console.WriteLine("ID of current Context: {0}", Thread.CurrentContext.ContextID); Console.WriteLine("Thread Name: {0}", primaryThread.Name); Console.WriteLine("Has thread started?: {0}", primaryThread.IsAlive); Console.WriteLine("Priority Level: {0}", primaryThread.Priority); Console.WriteLine("Thread State: {0}", primaryThread.ThreadState); }
}</source>
Starting a Method in a Separate Thread
<source lang="csharp">using System; using System.Threading; public class MainClass {
public const int Repetitions = 1000; public static void Main() { ThreadStart threadStart = new ThreadStart(DoWork); Thread thread = new Thread(threadStart); thread.Start(); for (int count = 0; count < Repetitions; count++) { Console.Write("-"); } thread.Join(); } public static void DoWork() { for (int count = 0; count < Repetitions; count++) { Console.Write("."); } }
}</source>
The creation of threads
<source lang="csharp">using System; using System.Threading; class MainClass {
public static void Countdown() { for (int i = 10; i > 0; i--) { Console.Write(i.ToString() + " "); } } public static void Main() { Thread t2 = new Thread(new ThreadStart(Countdown)); t2.Start(); }
}</source>
10 9 8 7 6 5 4 3 2 1
Thread method with no parameter
<source lang="csharp">using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime; using System.Runtime.rupilerServices; using System.Security; using System.Text; public class MainClass {
public static void Main() { Thread thread = new Thread(WorkerOperation); thread.Start(); thread.Join(); } private static void WorkerOperation() { Console.WriteLine("Simple worker"); }
}</source>
Simple worker
Thread method with parameter
<source lang="csharp">using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime; using System.Runtime.rupilerServices; using System.Security; using System.Text; public class MainClass {
public static void Main() { Thread paramThread = new Thread(ParameterizedWorkerOperation); paramThread.Start("Test"); paramThread.Join(); } private static void ParameterizedWorkerOperation(object o) { Console.WriteLine("Param worker: {0}", o); }
}</source>
Param worker: Test
Thread Stats
<source lang="csharp">using System; using System.Collections.Generic; using System.Text; using System.Threading;
class Program { static void Main(string[] args) { Thread primaryThread = Thread.CurrentThread; primaryThread.Name = "ThePrimaryThread"; Console.WriteLine("Name of current AppDomain: {0}",Thread.GetDomain().FriendlyName); Console.WriteLine("ID of current Context: {0}",Thread.CurrentContext.ContextID); Console.WriteLine("Thread Name: {0}",primaryThread.Name); Console.WriteLine("Has thread started?: {0}",primaryThread.IsAlive); Console.WriteLine("Priority Level: {0}",primaryThread.Priority); Console.WriteLine("Thread State: {0}",primaryThread.ThreadState); } }</source>
Use anonymous delegate as the worker method to create Thread
<source lang="csharp">using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime; using System.Runtime.rupilerServices; using System.Security; using System.Text; public class MainClass {
public static void Main() { int threadCount = 5; Thread[] threads = new Thread[threadCount]; for (int i = 0; i < threadCount; i++) { int idx = i; threads[i] = new Thread(delegate() { Console.WriteLine("Worker {0}", idx); }); } Array.ForEach(threads, delegate(Thread t) { t.Start(); }); }
}</source>
Worker 0 Worker 1 Worker 2 Worker 3 Worker 4