首先我们引入using System.Threading;
然后我们编写一个方法:
public
static
void
SimpleWorkerThread()
... {
for (int i = 0; ; i++)
...{
try
...{
Console.WriteLine("Hello from the worker thread.");
if (i > 1000)
...{
Thread.CurrentThread.Abort();
return;
}
}
catch (Exception e)
...{
Console.WriteLine(e.ToString() + " Exception caught.");
Thread.ResetAbort();
}
}
}
... {
for (int i = 0; ; i++)
...{
try
...{
Console.WriteLine("Hello from the worker thread.");
if (i > 1000)
...{
Thread.CurrentThread.Abort();
return;
}
}
catch (Exception e)
...{
Console.WriteLine(e.ToString() + " Exception caught.");
Thread.ResetAbort();
}
}
}
接着我们把这个方法改一个字.
public
static
void
SimpleWorkerThread1()
... {
for (int i = 0; ; i++)
...{
try
...{
Console.WriteLine("操!");
if (i > 1000)
...{
Thread.CurrentThread.Abort();
return;
}
}
catch (Exception e)
...{
Console.WriteLine(e.ToString() + " Exception caught.");
Thread.ResetAbort();
}
}
}
... {
for (int i = 0; ; i++)
...{
try
...{
Console.WriteLine("操!");
if (i > 1000)
...{
Thread.CurrentThread.Abort();
return;
}
}
catch (Exception e)
...{
Console.WriteLine(e.ToString() + " Exception caught.");
Thread.ResetAbort();
}
}
}
把这两个方法都放到类中去,
然后在Main()方法中添加:
static
void
Main(
string
[] args)
... {
ThreadStart S1 = new ThreadStart(SimpleWorkerThread);
ThreadStart S2 = new ThreadStart(SimpleWorkerThread1);
Thread T1 = new Thread(S1);
Thread T2 = new Thread(S2);
T1.Start();
T2.Start();
}
... {
ThreadStart S1 = new ThreadStart(SimpleWorkerThread);
ThreadStart S2 = new ThreadStart(SimpleWorkerThread1);
Thread T1 = new Thread(S1);
Thread T2 = new Thread(S2);
T1.Start();
T2.Start();
}
运行代码,是不是发现我们就可以一边做正经事一边操了?是不是很爽呢?