今天在做c#有关的东东的时候,遇到了线程的一些小问题,现在把最简单的线程的创建与启动,简单的总结如下 :
首先,要用到Thread类。。。Thread类位于System.Threading命名空间中。(ps:恕我废话),在包含命名空间以后,就开始创建啦。
public void <span style="color:#ff0000;">RunThread</span>()
{
for(int i=1;i<=10;i++)//总共运行十次
{
textBox1.Text += "Sample的work线程在运行"+i+"\r\n";
System.Threading.Thread.Sleep(1000);//每隔1秒运行一次
}
}
Thread thread = new Thread(<span style="color:#ff0000;">RunThread</span>);
thread.Start();
这样就可以啦,那么在来看看为毛要这么创建呢???
![生气](http://static.blog.csdn.net/xheditor/xheditor_emot/default/mad.gif)
![生气](http://static.blog.csdn.net/xheditor/xheditor_emot/default/mad.gif)
Thread类在实例化时,需要给其构造函数传入一个参数,用于指定线程开始执行的方法(线程入口)。我们查看Thread类的定义,发现其构造函数有以下重载形式:
在这里,我们使用下面这个构造函数来实例化Thread对象。
public Thread(ThreadStart start);
该构造函数接受一个ThreadStart 类型的入参。
查看ThreadStart 类型的定义,如下
public delegate void ThreadStart();
通过阅读定义,我们了解到,ThreadStart是一个委托类型,该委托类型封装的方法没有入参也没有返回值。
ThreadStart委托类型的定义同样位于System.Threading命名空间中。
到这里,我们可以简单总结一下Thread对象的实例化过程,包含以下步骤:
-
定义一个包含了要执行代码的方法,同时该方法必须具有和ThreadStart委托类型相同的签名(没有入参也没有返回值);
-
创建ThreadStart委托类型的委托实例;
-
实例化Thread对象,且将ThreadStart的委托实例作为入参传入Thread类的构造函数。
到这里小伙伴们知道了,前面我使用的创建线程的构造函数的类型,是委托。那么接下来我们还可以用另外一种很巧妙的方法,也很实用,来创建线程,代码如下所示:
Thread thread1 = new Thread(delegate() {
textBox1.Text += "启动的新的第"+(num++)+"个线程"+"\r\n";
});
thread1.Start();
直接给Thread的参数中,传入一个 匿名方法,这样在我们不想另外写入口方法的时候,很方便的实现线程的创建,
ok,总结到此结束啦。。。革命尚未成功
。。。。同志还需努力
。。。。。
![吐舌头](http://static.blog.csdn.net/xheditor/xheditor_emot/default/tongue.gif)
![委屈](http://static.blog.csdn.net/xheditor/xheditor_emot/default/wronged.gif)
![奋斗](http://static.blog.csdn.net/xheditor/xheditor_emot/default/struggle.gif)
![奋斗](http://static.blog.csdn.net/xheditor/xheditor_emot/default/struggle.gif)
![奋斗](http://static.blog.csdn.net/xheditor/xheditor_emot/default/struggle.gif)