.NET创建一个线程,是很简单的:
Thread workerThread = new Thread(StartThread);
创建了一个线程实例workerThread,其中它执行的方法是StartThread,
public static void StartThread()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Thread value {0} running on Thread Id {1}",
i.ToString(),
Thread.CurrentThread.ManagedThreadId.ToString());
}
}
然后当执行
workerThread.Start();
这句的时候线程开始启动,真正进入执行阶段。
很多的时候由于线程执行的过程中需要一定的时间,我们需要判断是否执行完毕是否,在单线程中,顺序执行即可,但是在多线程中,除了锁以外,控制稍微复杂,下面我就附上CodeProject上的一个用时间Timer类获取状态的小实例。
using System;
using System.Threading;
namespace CallBacks
{
class Program
{
private string message;
private static Timer timer;
private static bool complete;
static void Main(string[] args)
{
Program p = new Program();
Thread workerThread = new Thread(p.DoSomeWork);
workerThread.Start();
//create timer with callback
TimerCallback timerCallBack =
new TimerCallback(p.GetState);
timer = new Timer(timerCallBack, null,
TimeSpan.Zero, TimeSpan.FromSeconds(2));
//wait for worker to complete
do
{
//simply wait, do nothing
} while (!complete);
Console.WriteLine("exiting main thread");
Console.ReadLine();
}
public void GetState(Object state)
{
//not done so return
if (message == string.Empty) return;
Console.WriteLine("Worker is {0}", message);
//is other thread completed yet, if so signal main
//thread to stop waiting
if (message == "Completed")
{
timer.Dispose();
complete = true;
}
}
public void DoSomeWork()
{
message = "processing";
//simulate doing some work
Thread.Sleep(3000);
message = "Completed";
}
}
}
执行一个线程,然后隔两秒获取状态,判断该线程是否完成,请注意这里的
private static bool complete;
这句。
天气:大雨,ccdot发表于2008-5-19 9:14:31,阅读了565次,共有个0回复.