C#多线程学习总结
介绍:C#中,可以使用Thread类来处理(包含创建,启动,挂起,恢复,终止等操作)线程。本文将介绍如何使用Thread类来创建与启动新线程。
Thread类类位于System.Threading命名空间中。
1.基本函数
1.1常用函数
构造函数
public Thread(ThreadStart start);
public Thread(ParameterizedThreadStart start);
public Thread(ParameterizedThreadStart start, int maxStackSize);
public Thread(ThreadStart start, int maxStackSize);
第一个函数市我们最常用到的函数,这里介绍一下,参数ThreadStart是一个委托类型,该委托类型封装的方法没用参数也没有返回值。初始化线程时使用具有相同签名的函数来创建ThreadStart委托的委托实例,在将其作为参数作为来初始化该线程。那么一旦线程启动就会执行这个函数。如下:
static void sum()
{
//what do you want
}
Thread t = new Thread(new ThreadStart(sum)); //创建一个线程实例
线程启动函数
t.start(); //用于启动一个线程
线程挂起函数,线程被挂起后,操作被停止或者进入休眠状态。被挂起的线程不会占用任何处理器时间。可以用线程恢复函数恢复执行。
t.Suspend();//用于挂起线程,
线程恢复函数,可以用于恢复被挂起的线程
t.Resume();//恢复线程
线程中止函数,线程被中止,就停止运行,是无法恢复的。因为操作系统会删除该线程所有信息
t.Abort();
线程阻塞函数,会阻塞线程,当没有参数时,会阻塞到另一个线程执行完毕,当有参数时会阻塞该线程一段时间(由参数决定)
t.Join();
t.Join(1000); //重载实现public bool Joint(int millisecondsTimeout)
1.2静态函数
1.3属性
1.4静态属性
上述例子完整代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ThreadExample1
{
class Program
{
static void sum()
{
int sum = 0;
for (int i = 1; i < 1000000; i++)
{
sum += i;
if (i % 100000 == 0)
{
Console.WriteLine("sum : {0} i : {1}", sum, i);
}
}
}
static void que()
{
int que = 0;
for (int i = 1000000; i > 0; i--)
{
que -= i;
if (i % 100000 == 0)
{
Console.WriteLine("que : {0} i : {1}", que, i);
}
}
}
static void Main(string[] args)
{
Thread t1 = new Thread(new ThreadStart(sum));
t1.Start();
//t1.Suspend();
//t1.Resume();
//t1.Join();
//t1.Join(1000);
//t1.Abort();
que();
}
}
}
2.传参
这里一个参数的话很简单,用ParameterizedThreadStart构造Thread构造函数的参数即可,这里我不列出代码。但这样的话,两个参数,多个参数呢?最先想到的肯定是用一个类或者结构体来封装我们的参数,但有一种更好的办法是用匿名函数(就像C++中我们最熟悉的函数指针,objective-C中的代码块),代码如下 :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ThreadExample1
{
class Function
{
public static Function Current
{
get
{
return new Function();
}
set{ }
}
public string outPutExcel(string a, long? b, string c)
{
System.Console.WriteLine("start");
Thread.Sleep(10000);
System.Console.WriteLine("end");
return a + b.ToString() + c;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ThreadExample1
{
class Program
{
public static void Main()
{
string a = "a";
long b = 1;
string c = "c";
Thread t1 = new Thread(new ThreadStart(delegate
{
var result = Function.Current.outPutExcel(a, b, c);
map.Add(1.ToString(), result);
}));
t1.Start();
var result1 = getResult();
System.Console.WriteLine(result1);
}
private static Dictionary<string, string> map = new Dictionary<string, string>();
private static string getResult()
{
string result = null;
while (true)
{
if (!map.ContainsKey("1"))
{
Thread.Sleep(1000);
}
else
{
result = map["1"];
if (result != null)
break;
}
}
return result;
}
}
}
3.
未完成 先留坑