C#线程操作的各个方法
在UI事件后需要执行大量耗费时间的代码时,通常需要将此代码放入线程中去执行,本文着重讲一下从线程的创建到执行及终止的一系列操作。
一、线程的创建。
线程创建分为带参数线程与不带参数线程,带参数时需要用object做封装,多个参数使用object[] data,以下为代码
// 无参数函数
public static void ParaMeterFreeMethod()
{
Console.WriteLine("this is a not Parameter Fun");
}
// 带参数函数
public static void ParameterMethod(object data)
{
string myRealData = data as string; // 拆箱操作
Console.WriteLine("this is a have Parameter Method, the Para is: " + myRealData);
}
static void Main()
{
Thread t1 = new Thread(ParaMeterFreeMethod);
Thread t2 = new Thread(new ParameterizedThreadStart(ParameterMethod));
t1.BackGround = true;
t2.BackGround = true;
t1.Start(); // 启动无参数线程
t2.Start("hello thred"); // 启动带参数线程
}
二、线程的异步执行
在线程的异步执行中,主要使用两种方式,一种为创建委托使用BeginInvoke,看需求再看是否添加回调函数;第二种使用窗体中提供的一个封装类,BackgroundWoker类,在该类中已经对主操作和回调函数做了封装,只需要调用即可。
1、BackGroundWoker封装
class AsynThread
{
public BackgroundWorker bw = new BackgroundWorker();
public AsynThread()
{
bw.DoWork += new DoWorkEventHandler(BwDoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BwWorkCompleted);
}
private void BwDoWork(object sender, DoWorkEventArgs e)
{
for(int i = 0; i < 100; i++)
{
Console.WriteLine("background thread , value: " + i);
Thread.Sleep(30);
}
}
private void BwWorkCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Console.WriteLine("background thread finshed");
}
}
// 主函数中调用
static void Main()
{
AsynThread myThead = new AsynThread();
myThead.bw.RunWorkerAsync();
AsynTheadBiginInvoke.DoWorkMethod(100);
for(int i = 0; i < 50; i++)
{
Console.WriteLine("Main thread , value: " + i);
Thread.Sleep(5);
}
Console.WriteLine("Main thread finished");
}
2、使用beginInvoke进行异步调用
delegate string MethodDelegate(int iCallTime);
public static class AsynTheadBiginInvoke
{
public static string LongRunningMethod(int iCallTime)
{
for(int i = 0; i < iCallTime; i++)
{
Console.WriteLine("back thread , value: " + i);
Thread.Sleep(50);
}
return "MyCallTime was:" + iCallTime.ToString();
}
public static void DoWorkMethod(int myTime)
{
MethodDelegate dlgt = new MethodDelegate(LongRunningMethod);
AsyncCallback asyCallBack = new AsyncCallback(MethodCompleted);
IAsyncResult iar = dlgt.BeginInvoke(20, asyCallBack, dlgt);
}
public static void MethodCompleted(IAsyncResult iar)
{
string str = null;
MethodDelegate dlgt = (MethodDelegate)iar.AsyncState;
str = dlgt.EndInvoke(iar);
Console.WriteLine("long time work completed!");
}
}
static void Main(string[] args)
{
AsynTheadBiginInvoke.DoWorkMethod(100);
for(int i = 0; i < 50; i++)
{
Console.WriteLine("Main thread , value: " + i);
Thread.Sleep(5);
}
Console.WriteLine("Main thread finished");
Console.ReadKey();
}
此时执行主函数时,调用完DoWorkMethod()函数后马上执行后边的语句,执行完后会自动调用Methcompleted()方法,通过endInvoke拿到返回值,而若需要在执行beginInvoke就拿到值,需要将回调函数置为null,然后执行beginInvoke后线程会阻塞等待委托的函数执行完后,才执行后续的语句,包括主线程也会被阻塞