c#

位置:IT落伍者 >> c# >> 浏览文章

Visual C#中编写多线程程序之起步


发布日期:2021年01月05日
 
Visual C#中编写多线程程序之起步

net将关于多线程的功能定义在SystemThreading名字空间中因此要使用多线程必须先声明引用此名字空间(using SystemThreading;)

即使你没有编写多线程应用程序的经验也可能听说过启动线程杀死线程这些词其实除了这两个外涉及多线程方面的还有诸如暂停线程优先级挂起线程恢复线程等等下面将一个一个的解释

a启动线程

顾名思义启动线程就是新建并启动一个线程的意思如下代码可实现

Thread thread = new Thread(new ThreadStart( Count));

其中的 Count 是将要被新线程执行的函数

b杀死线程

杀死线程就是将一线程斩草除根为了不白费力气在杀死一个线程前最好先判断它是否还活着(通过 IsAlive 属性)然后就可以调用 Abort 方法来杀死此线程

c暂停线程

它的意思就是让一个正在运行的线程休眠一段时间如 threadSleep(); 就是让线程休眠秒钟

d优先级

这个用不着解释了Thread类中有一个ThreadPriority属性它用来设置优先级但不能保证操作系统会接受该优先级一个线程的优先级可 分为Normal AboveNormal BelowNormal Highest Lowest具体实现例子如下:

threadPriority = ThreadPriorityHighest;

e挂起线程

Thread类的Suspend方法用来挂起线程知道调用Resume此线程才可以继续执行如果线程已经挂起那就不会起作用

if (threadThreadState = ThreadStateRunning)

{

threadSuspend();

}

f恢复线程

用来恢复已经挂起的线程以让它继续执行如果线程没挂起也不会起作用

if (threadThreadState = ThreadStateSuspended)

{

threadResume();

}

下面将列出一个例子以说明简单的线程处理功能此例子来自于帮助文档

using System;

using SystemThreading;

// 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 = ; i < ; i++)

{

ConsoleWriteLine(ThreadProc: {} i);

// Yield the rest of the time slice

ThreadSleep();

}

}

public static void Main()

{

ConsoleWriteLine(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 ThreadSleep that follows tStart() to see the difference

tStart();

//ThreadSleep();

for (int i = ; i < ; i++)

{

ConsoleWriteLine(Main thread: Do some work);

ThreadSleep();

}

ConsoleWriteLine(Main thread: Call Join() to wait until ThreadProc ends);

tJoin();

ConsoleWriteLine(Main thread: ThreadProcJoin has returned Press Enter to end program);

ConsoleReadLine();

}

}

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

Main thread: Start a second thread

Main thread: Do some work

ThreadProc:

Main thread: Do some work

ThreadProc:

Main thread: Do some work

ThreadProc:

Main thread: Do some work

ThreadProc:

Main thread: Call Join() to wait until ThreadProc ends

ThreadProc:

ThreadProc:

ThreadProc:

ThreadProc:

ThreadProc:

ThreadProc:

Main thread: ThreadProcJoin has returned Press Enter to end program

上一篇:Visual Studio中对Linux应用进行远程调试

下一篇:几个C#编程的小技巧 (下)