.net 多线程的四种实现方式

.net中创建多线程可以有四种方式:

Thread类、委托、ThreadPool类、Task类

Thread类创建多线程
///
/// Thread类启动
///
public static void Thread_Start()
{
Thread thread = new Thread(new ParameterizedThreadStart(AddA));
thread.Start(“Thread”);
}

委托方式创建多线程
delegate void Delegate_Add(Object stateInfo);
///
/// 委托方式启动
///
public static void Delegate_Start()
{
Delegate_Add dele_add = AddA;
dele_add.BeginInvoke(“Delegate”, null,null);
}

ThreadPool类创建多线程
///
/// 线程池方式启动
///
public static void ThreadPool_Start()
{
WaitCallback w = new WaitCallback(AddA);
ThreadPool.QueueUserWorkItem(w,“ThreadPool”);
}

Task类创建多线程
///
/// Task方式启动
///
public static void Task_Start()
{
Action add_Action = AddA;
Task task = new Task(add_Action, “Task”);
task.Start();
}

IsBackground
  所有的多线程操作,必定有一个主线程,主线程(ParentThread)与子线程(ChildThread)的生命周期也是相互作用的,

子线程中的IsBackground属性,决定了两类线程生命周期的依赖关系。

如果ChildThread.IsBackGround=true,ParentThread结束时,ChildThread也会终止;

如果ChildThread.IsBackGround=false,ParentThread必须等ChildThread终止后才会终止。

对于这四种多线程方法,默认生成线程的IsBackGround有所不同:

类型IsBackGround
Thread类false
委托true
ThreadPool类true
Task类true

辅助方法

public static int a;
static void Main(string[] args)
{

MultiThreadDemo demo = new MultiThreadDemo();
Console.WriteLine("Main Thread ID:" + Thread.CurrentThread.ManagedThreadId);
MultiThreadTest();

Thread.Sleep(10000);
Console.WriteLine("a:" + a);
Console.WriteLine("Main thread exits.");

}
///
/// 打印当前线程信息
///
public static void PrinctCurrentThreadInfo()
{
var t = Thread.CurrentThread;
Console.WriteLine(“Current Thread ID:” + t.ManagedThreadId);
Console.WriteLine(“Is Back Ground:{0}”, t.IsBackground);
Console.WriteLine(“Thread Priority:” + t.Priority.ToString());
Console.WriteLine(“Thread State:” + t.ThreadState.ToString());

}

///
/// 测试方法
///
///
public static void AddA(Object stateInfo)
{

Console.WriteLine("{0,-20} Thread ID:{1}", stateInfo.ToString(), Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("IsBackground:{0}\n", Thread.CurrentThread.IsBackground);

while (a < 10)
{
    Console.WriteLine("{0,-20} Start :{1}", stateInfo.ToString(), a);
    Thread.Sleep(10);
    a++;
    Console.WriteLine("{0,-20} End   :{1}\n", stateInfo.ToString(), a);
}

Console.WriteLine("{0,-20} Thread ID:{1} Result:{2}", stateInfo.ToString(), Thread.CurrentThread.ManagedThreadId, a);
return;

}

///
/// 多线程测试
///
public static void MultiThreadTest()
{
a = 0;
Thread_Start();
Delegate_Start();
ThreadPool_Start();
Task_Start();
}

转载于:https://www.cnblogs.com/lvjianwei/p/5773118.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值