菜鸟问一个关于线程的问题
using System;using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace ThreadTest
{
public class Alpha
{
public void Beta()
{
while (true)
{
Console.WriteLine("Alpha.Beta is running in its own thread.");
}
}
};
public class Simple
{
public static int Main()
{
Console.WriteLine("Thread Start/Stop/Join Sample");
Alpha oAlpha = new Alpha();
Thread oThread = new Thread(new ThreadStart(oAlpha.Beta));
Console.WriteLine(oThread.ThreadState);
oThread.Start();
while (!oThread.IsAlive)
Thread.Sleep(1); //暂停1毫秒
Console.WriteLine(oThread.ThreadState);
oThread.Abort(); //终止此线程
Console.WriteLine(oThread.ThreadState);
oThread.Join();//主线程等待,直到oThread线程结束
Console.WriteLine(oThread.ThreadState);
Console.WriteLine();
Console.WriteLine("Alpha.Beta has finished");
try
{
Console.WriteLine("Try to restart the Alpha.Beta thread");
Console.WriteLine(oThread.ThreadState);
// oThread.Start();
// oThread.Resume();
Console.WriteLine(oThread.ThreadState);
}
catch (ThreadStateException)
{
Console.WriteLine("ThreadStateException trying to restart Alpha.Beta. ");
Console.WriteLine("Expected since aborted threads cannot be restarted.");
Console.ReadLine();
}
return 0;
}
}
}
想问问各位大哥大姐,怎么让线程在try块里启动呢?还是不能在cry块里启动呀?为什么在线等,谢谢! --------------------编程问答-------------------- // oThread.Start();
// oThread.Resume();
用这两个都不行,Console.WriteLine(oThread.ThreadState); 查看状态还是stopped。。 --------------------编程问答-------------------- Thread oThread = new Thread(oAlpha.Beta);
oThread.Start();
即可启动 --------------------编程问答-------------------- oThread.Abort(); //终止此线程
有可能已经出现异常,你没捕获呢 --------------------编程问答--------------------
你运行下,捕获了。。 --------------------编程问答--------------------
可以 不过要把 OThread 改名 否则提示:错误 1 不能在此范围内声明名为“oThread”的局部变量,因为这样会使“oThread”具有不同的含义,而它已在“父级或当前”范围中表示其他内容了 D:\NET\ConsoleApplication5\ConsoleApplication5\Program.cs 46 24 ConsoleApplication5
--------------------编程问答--------------------
绝对不能重名!
补充:.NET技术 , C#