线程,通俗的讲是指程序在一个时间点内处理事物的能力,多线程,指程序能够同一时间点处理多种事物。
C#中的线程使用于System.Threading命名空间下。
一.通过Thread类创建线程:
支持无参函数和参数为object类型的函数。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ThreadTest
{
class Person
{
public Person ()
{
Thread t = new Thread(Speak);
t.Start();
}
private void Speak ()
{
Console.WriteLine("Person speak");
}
}
}
参数为object类型的函数:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ThreadTest
{
class Person
{
public Person()
{
Thread t = new Thread(Speak);
t.Start("haha");
}
private void Speak(object aa)
{
Console.WriteLine(aa);
}
}
}
那么,如何通过Thread创建能传递多个参数的线程呢?
1.封装函数结构:
新建CustomThread类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ThreadTest
{
class CustomThread
{
private string paramStr;
private int paramInt;
public CustomThread (string paramStr, int paramInt)
{
this.paramStr = paramStr;
this.paramInt = paramInt;
Thread t = new Thread(Work);
t.Start();
}
private void Work ()
{
Console.WriteLine("paramStr:" + paramStr + " paramInt:" + paramInt);
}
}
}
这样封装一下Thread,把需要的参数通过构造函数存到CustomThread中,达到实例化多参数线程的目的。
2.使用委托:
通过委托的BeginInvoke可以开启一个后台委托,接受一个回调函数,并在EndInvoke中返回函数返回值,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ThreadTest
{
class Person
{
Func<int, int> func;
public Person()
{
func = Cal;
func.BeginInvoke(1, args => {
int result = func.EndInvoke(args);
Console.WriteLine("结果为: " + result);
}, null);
}
private int Cal (int num)
{
Thread.Sleep(2000);
return num + 1;
}
}
}
注意,这里主线程如果执行结束,这个后台委托也会被停止!