您的位置:首页 > 编程语言 > C#

C#构建多线程应用程序(2) —— System.Threading命名空间

2016-02-17 10:00 671 查看

在.NET平台下,System.Threading命名空间提供了许多类型来构建多线程应用程序。

1.以编程方式创建次线程


当希望以编程方式创建次线程以分担一些任务时,可以遵从下面的预定的步骤:
(1)
创建一个方法作为新线程的入口点;
(2)
创建一个ParameterizedThreadStart或者ThreadStart委托,并把在上一步所定义方法的地址传递给委托的构造函数;
(3)
创建一个Thread对象,并把ParameterizedThreadStart或者ThreadStart委托作为构造函数的参数;
(4)
建立任意初始化线程的特性(名称、优先级等);
(5)
调用Thread.Start()方法。
按照步骤(2)的规定,可以使用两种不同的委托类型指向将在次线程中执行的方法。ThreadStart委托指向一个没有参数、没有返回值的方法。ParameterizedThreadStart委托类型允许包含一个System.Object类型的参数。由于C#任何对象都源于Syatem.Object,所以可以通过一个自定义的类或结构来传递任意数量的参数。ParameterizedThreadStart委托仅仅指向无返回值的方法。

下面是一个使用ThreadStart委托实现的一个简单的多线程示例代码:

<span style="font-size:12px;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ThreadStart1
{
class Program
{
static void SleepTime()
{
int i = 0;
while (true)
{
Thread.Sleep(1000);
Console.WriteLine("Sleep for {0} seconds!", ++i);

if (i > 5) break;
}
}

static void Main(string[] args)
{
//创建线程
Thread SleepThread = new Thread(new ThreadStart(SleepTime));

//设置Name属性
SleepThread.Name = "MySleepTime";

//启动线程
SleepThread.Start();

Console.WriteLine("the sleep thread is over!");

Console.ReadLine();
}
}
}</span>

运行结果如下显示:



使用ParameterizedThreadStart委托实现的一个简单的多线程示例代码如下:
<span style="font-size:12px;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ThreadStart1
{
class Program
{
static void SleepTime(Object n)
{
int i = 0;
while (true)
{
Thread.Sleep(1000);
Console.WriteLine("Sleep for {0} seconds!", ++i);

if (i > (int)n) break;
}
}

static void Main(string[] args)
{
//创建线程
Thread SleepThread = new Thread(new ParameterizedThreadStart(SleepTime));

//设置Name属性
SleepThread.Name = "MySleepTime";

//启动线程
SleepThread.Start(3);

Console.WriteLine("the sleep thread is over!");

Console.ReadLine();
}
}
}</span>

运行结果如下:



2. AutoResetEvent类

主线程判断次线程是否结束,一个简单、安全的方法是使用AutoResetEvent类。它可以强制主线程等待,直到次线程结束。
在主线程当中,创建AutoResetEvent类的实例,向构造函数传入false,表示尚未收到通知,然后在需要等待的地方调用WaitOne()方法。当次线程完成任务时,调用AutoResetEvent类型实例的Set()方法,表示收到通知。
以下示例展示了使用AutoResetEvent类的一个简单示例:

<span style="font-size:12px;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace SimpleMultiThreadApp
{
class Program
{
//初始化为false,表示事件为非终止状态
private static AutoResetEvent waitHandle = new AutoResetEvent(false);

static void SleepTime()
{
int i = 0;
while (true)
{
Thread.Sleep(1000);
Console.WriteLine("Sleep for {0} seconds!", ++i);

if (i > 5)
{
//将事件状态设置为终止状态,表示运行结束
waitHandle.Set();
break;
}
}
}

static void Main(string[] args)
{
//创建线程
Thread SleepThread = new Thread(new ThreadStart(SleepTime));

//设置Name属性
SleepThread.Name = "MySleepTime";

//启动线程
SleepThread.Start();

//等待,直到事件设为终止状态
waitHandle.WaitOne();
Console.WriteLine("the sleep thread is over!");

Console.ReadLine();
}
}
}</span>
运行结果如下:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息