(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
An alternate way to start a thread: start a thread in its own constructor
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 mt = new MyThread("Child #1");
do {
Console.Write(".");
Thread.Sleep(100);
} while (mt.count != 10);
Console.WriteLine("Main thread ending.");
}
}
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.
Simple Thread with ThreadStart
using System;
using System.Threading;
class MainClass
{
public static void DoCount()
{
for ( int i = 0; i < 10; i++ )
{
System.Console.WriteLine( "Reached {0}", i );
}
}
[STAThread]
static void Main(string[] args)
{
Thread t = new Thread( new ThreadStart( DoCount ) );
t.Start();
}
}
Reached 0
Reached 1
Reached 2
Reached 3
Reached 4
Reached 5
Reached 6
Reached 7
Reached 8
Reached 9
thread.IsAlive
using System;
using System.Threading;
public class ThreadState {
static void WorkerFunction() {
for (int i = 1; i < 50000; i++) {
Console.WriteLine("Worker: " + Thread.CurrentThread.ThreadState);
}
}
static void Main() {
string ThreadState;
Thread t = new Thread(new ThreadStart(WorkerFunction));
t.Start();
while (t.IsAlive) {
Console.WriteLine("Still waiting. I"m going back to sleep.");
Thread.Sleep(200);
}
Console.WriteLine(t.ThreadState);
}
}