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

C# 线程

2013-11-18 11:14 155 查看

线程的方法和状态

Thread类常用方法:

Start();启动线程

Sleep(int);静态方法,暂停当前线程指定ms数

Abort();通常使用该方法来终止一个线程

Suspend();该方法并不终止未完成的线程,它仅仅挂起线程,以后可以恢复

Resume();恢复被Suspend()方法挂起的线程执行

新建线程

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Thread
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("主进程开始");

//声明一个新的线程,可以叫辅助线程
System.Threading.Thread newthread = new System.Threading.Thread(PrintMethod);

//启动线程,并传递委托所需要的参数
newthread.Start("我是新线程哦!");
}

public static void PrintMethod(object msg)
{
Console.WriteLine(msg);
}
}
}


龟兔赛跑例子

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ThreadTest
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("老龟我(主线程)开始跑");

//声明一个新的线程,可以叫辅助线程
Thread newthread = new System.Threading.Thread(Gotobed);

//启动线程,并传递委托所需要的参数
newthread.Start("兔哥哥");

for (int i = 0; i < 10; i++)
{
Console.WriteLine("老龟我继续跑!继续跑!再跑!");
Thread.Sleep(100);
}

Console.WriteLine("终于到终点了,2B兔子还没到,木哈哈!!!~~");
}

public static void Gotobed(object date)
{
Console.WriteLine("那家伙跑的太慢了,"+date.ToString()+"我睡会儿觉先");

for (int i = 0; i < 15; i++)
{
Console.WriteLine("小兔子。。ZZZ。。。ZZZ");
Thread.Sleep(100);
}
Console.WriteLine("都睡了1500年了,那家伙还没来,啊???你怎么在我前面?");
}
}
}


进程的状态ThreadState

Aborted;线程已经停止

AbortRequested;线程Abort方法已经被调用,但是线程还未停止;

Background;线程在后台执行,与属性Thread.IsBackground有关;

Running;线程正在正常运行

Stopped;线程已经倍停止

StopRequested;线程正在倍要求停止

Suspended;线程已经倍挂起

SuspendRequested;线程正在要求倍挂起,但是未来得及响应

Unstarted;未调用Start开始进程

WaitSleepJoin;线程因为调用了Wait(),Sleep(),Join()等方法处于封锁状态

代码获取线程信息

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ThreadTest
{
class Program
{
static void Main(string[] args)
{
Thread t = Thread.CurrentThread;
if (t.Name == null || t.Name == "")
t.Name = "主线程";
string info = string.Format(
"当前线程信息如下\n线程名:{0},\n优先级:{1},\n标识符:{2},\n状态{3},\n是否为后台线程{4},\n是否托管与线程池{5}"
,t.Name,t.Priority,t.ManagedThreadId,t.IsAlive,t.IsBackground,t.IsThreadPoolThread
);
Console.WriteLine(info);

Thread newt1 = new Thread(PrintCurrentInfo);
newt1.Start(newt1);
}

public static void PrintCurrentInfo(object newt1)
{
Thread t = (Thread)newt1;
t.Name = "新线程";
string info = string.Format(
"当前线程信息如下\n线程名:{0},\n优先级:{1},\n标识符:{2},\n状态{3},\n是否为后台线程{4},\n是否托管与线程池{5}"
, t.Name, t.Priority, t.ManagedThreadId, t.IsAlive, t.IsBackground, t.IsThreadPoolThread
);
Console.WriteLine(info);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: