Csharp Simple Thread Test
I copied and modified an example from MSDN: [1] on how to do a simple threading exercise:
First a class that writes his name on the console:
using System;
using System.Threading;
public class Writer
{
string m_name;
int m_sleep;
public Writer(string name, int sleep)
{
m_name = name;
m_sleep = sleep;
}
public void Write()
{
while (true)
{
Console.Write(m_name);
Thread.Sleep(m_sleep);
}
}
}
Then a simple main that initializes two writes in their own threads. Then stop the thread.
public class SimpleThreadTester
{
public static int Main()
{
Writer A = new Writer("A", 1);
Writer B = new Writer("B", 100);
Thread tA = new Thread(new ThreadStart(A.Write));
Thread tB = new Thread(new ThreadStart(B.Write));
tA.Start();
while (!tA.IsAlive)
;
tB.Start();
while (!tB.IsAlive)
;
Thread.Sleep(10000);
tA.Abort();
tA.Join();
Console.WriteLine(System.Environment.NewLine + "tA has finished");
Thread.Sleep(50);
tB.Abort();
tB.Join();
Console.WriteLine(System.Environment.NewLine + "tB has finished");
return 0;
}
}
Download source code here: [2]
Tillhör Kategori Programmering