首页 > 开发 > 综合 > 正文

在C#中编写多线程应用程序,简单!

2024-07-21 02:19:09
字体:
来源:转载
供稿:网友

(欢迎访问www.kunwsoft.com)
以前在使用vb来实现多线程的时候,发现有一定的难度。虽然也有这样那样的方法,但都不尽人意,但在c#中,要编写多线程应用程序却相当的简单。这篇文章将作简要的介绍,以起到抛砖引玉的作用!
.net将关于多线程的功能定义在system.threading名字空间中。因此,要使用多线程,必须先声明引用此名字空间(using system.threading;)。
即使你没有编写多线程应用程序的经验,也可能听说过“启动线程”“杀死线程”这些词,其实除了这两个外,涉及多线程方面的还有诸如“暂停线程”“优先级”“挂起线程”“恢复线程”等等。下面将一个一个的解释。
a.启动线程
顾名思义,“启动线程”就是新建并启动一个线程的意思,如下代码可实现:
thread thread1 = new thread(new threadstart( count));
其中的 count 是将要被新线程执行的函数。
b.杀死线程
“杀死线程”就是将一线程斩草除根,为了不白费力气,在杀死一个线程前最好先判断它是否还活着(通过 isalive 属性),然后就可以调用 abort 方法来杀死此线程。
c.暂停线程
它的意思就是让一个正在运行的线程休眠一段时间。如 thread.sleep(1000); 就是让线程休眠1秒钟。
d.优先级
这个用不着解释了。thread类中有一个threadpriority属性,它用来设置优先级,但不能保证操作系统会接受该优先级。一个线程的优先级可分为5种:normal, abovenormal, belownormal, highest, lowest。具体实现例子如下:
thread.priority = threadpriority.highest;
e.挂起线程
thread类的suspend方法用来挂起线程,知道调用resume,此线程才可以继续执行。如果线程已经挂起,那就不会起作用。
if (thread.threadstate = threadstate.running)?
{
thread.suspend();
}
f.恢复线程
用来恢复已经挂起的线程,以让它继续执行,如果线程没挂起,也不会起作用。
if (thread.threadstate = threadstate.suspended)?
{
thread.resume();
}
下面将列出一个例子,以说明简单的线程处理功能。此例子来自于帮助文档。
using system;
using system.threading;

// simple threading scenario:? start a static method running
// on a second thread.
public class threadexample {
// the threadproc method is called when the thread starts.
// it loops ten times, writing to the console and yielding?
// the rest of its time slice each time, and then ends.
public static void threadproc() {
for (int i = 0; i < 10; i++) {
console.writeline("threadproc: {0}", i);
// yield the rest of the time slice.
thread.sleep(0);
}
}

public static void main() {
console.writeline("main thread: start a second thread.");
// the constructor for the thread class requires a threadstart?
// delegate that represents the method to be executed on the?
// thread.? c# simplifies the creation of this delegate.
thread t = new thread(new threadstart(threadproc));
// start threadproc.? on a uniprocessor, the thread does not get?
// any processor time until the main thread yields.? uncomment?
// the thread.sleep that follows t.start() to see the difference.
t.start();
//thread.sleep(0);

for (int i = 0; i < 4; i++) {
console.writeline("main thread: do some work.");
thread.sleep(0);
}

console.writeline("main thread: call join(), to wait until threadproc ends.");
t.join();
console.writeline("main thread: threadproc.join has returned.? press enter to end program.");
console.readline();
}
}

此代码产生的输出类似如下内容:

main thread: start a second thread.
main thread: do some work.
threadproc: 0
main thread: do some work.
threadproc: 1
main thread: do some work.
threadproc: 2
main thread: do some work.
threadproc: 3
main thread: call join(), to wait until threadproc ends.
threadproc: 4
threadproc: 5
threadproc: 6
threadproc: 7
threadproc: 8
threadproc: 9
main thread: threadproc.join has returned. press enter to end program.?
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表