【多线程】C#多线程

一、关于c#多线程的使用

在实例化Thread的实例时,需要提供一个委托,在实例化这个委托时所用到的参数是线程将来启动时要运行的方法,在.net中提供了两种启动线程的方式,一种为带参启动,一种为不带参启动。

1、不带参数的启动方式

使用ThreadStart委托启动线程。

using UnityEngine;
using System.Collections;
using System.Threading;
using System;

public class ThreadOne : MonoBehaviour {
	
	void Start () 
	{
		InVokeThreadOne();
	}

	void InVokeThreadOne()
	{
		Thread _trdOne = new Thread(new ThreadStart(MethodOne));
		_trdOne.Name = "threadOne";
		_trdOne.Start();
	}

	void MethodOne()
	{
		for(int i = 0 ;i<10;i++)
		{
			print(DateTime.Now);
			Thread.Sleep(1000);
		}
	}
}

2、带参数的启动方式

使用ParameterizedThreadStart委托来启动线程。

using UnityEngine;
using System.Collections;
using System.Threading;
using System;

public class ThreadOne : MonoBehaviour {
	
	void Start () 
	{
		InVokeThreadTwo();
		InVokeThreadThree();
		InVokeThreadFour();
	}
	
	void InVokeThreadTwo()
	{
		Thread _trdTwo = new Thread(new ParameterizedThreadStart(MethodTwo));
		_trdTwo.Name = "treadTwo";
		_trdTwo.Start(2000);
	}

	void InVokeThreadThree()
	{
		Thread _trdThree = new Thread(new ParameterizedThreadStart(MethodThree));
		_trdThree.Name = "treadThree";
		_trdThree.Start(new ThreadParams(1000,10));
	}

	void InVokeThreadFour()
	{
		ThreadParamsTwo _cTrdParms = new ThreadParamsTwo(1000,10);
		_cTrdParms.Start();
	}
	
	void MethodTwo( object m_iSleepTime)
	{
		int m_iTime = int.Parse(m_iSleepTime.ToString());
		for(int i = 0 ;i<10;i++)
		{
			print(DateTime.Now);
			Thread.Sleep(m_iTime);
		}
	}

	void MethodThree( object m_cThreadParm)
	{
		ThreadParams m_cTParm = (ThreadParams) m_cThreadParm;
		for(int i = 0 ;i<m_cTParm.LoopCount;i++)
		{
			print(DateTime.Now);
			Thread.Sleep(m_cTParm.SleepTime);
		}
	}
	
	class ThreadParams
	{
		private int _iSleepTime;
		private int _iLoopCount;

		public int SleepTime
		{
			get
			{
				return _iSleepTime;
			}
		}

		public int LoopCount
		{
			get
			{
				return _iLoopCount;
			}
		}

		public ThreadParams( int m_iSleepTime,int m_iLoopCount)
		{
			_iSleepTime = m_iSleepTime;
			_iLoopCount = m_iLoopCount;
		}

	}
	class ThreadParamsTwo
	{
		private int _iSleepTime;
		private int _iLoopCount;
		private Thread _trdFour;
		
		public int SleepTime
		{
			get
			{
				return _iSleepTime;
			}
		}
		
		public int LoopCount
		{
			get
			{
				return _iLoopCount;
			}
		}
		
		public ThreadParamsTwo( int m_iSleepTime,int m_iLoopCount)
		{
			_iSleepTime = m_iSleepTime;
			_iLoopCount = m_iLoopCount;
			_trdFour = new Thread(new ThreadStart(ThreadRun));
		}

		void ThreadRun()
		{
			for(int i = 0 ;i< _iLoopCount;i++)
			{
				print(DateTime.Now);
				Thread.Sleep(_iSleepTime);
			}
		}

		public void Start()
		{
			_trdFour.Start();
		}
	}
}

二、多线程常用函数

启动线程Start

挂起线程Suspend

休眠线程Sleep

恢复挂起Resume

终止线程Abord

等待线程中止Join


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值