创建线程的几种方法:
1 异步委托
创建线程的一种简单方式是定义一个委托,并异步调用它。 委托是方法的类型安全的引用。Delegate类 还支持异步地调用方法。在后台,Delegate类会创建一个执行任务的线程。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace _016_线程_委托方式发起线程
{
class Program
{
//一般我们会为比较耗时的操作 开启单独的线程去执行,比如下载操作
static int Test(int i, string str)
{
Console.WriteLine("test:" + i + str);
Thread.Sleep(100);//让当亲线程休眠(暂停线程的执行) 单位ms
return 100;
}
static void Main(string[] args)
{//在main线程中执行 一个线程里面语句的执行 是从上到下的
// 通过委托 开启一个线程
Func<int, string, int> a = Test;
// 开启一个新的线程去执行 a所引用的方法
IAsyncResult ar = a.BeginInvoke(100, " mytest", null, null);
// IAsyncResult 可以取得当前线程的状态
Console.WriteLine("main");
while (ar.IsCompleted == false)//如果当前线程没有执行完毕
{
Console.Write(".");
Thread.Sleep(10); //控制子线程的检测频率
}
int res = a.EndInvoke(ar);//取得异步线程的返回值
Console.WriteLine(res);
}
}
}
输出结果:
上面是通过循环检测判断线程是否结束。当我们通过BeginInvoke开启一个异步委托的时候,返回的结果是IAsyncResult,我们可以通过它的AsyncWaitHandle属性访问等待句柄。这个属性返回一个WaitHandler类型的对象,它中的WaitOne()方法可以等待委托线程完成其任务,WaitOne方法可以设置一个超时时间作为参数(要等待的最长时间),如果发生超时就返回false。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace _016_线程_委托方式发起线程
{
class Program
{
//一般我们会为比较耗时的操作 开启单独的线程去执行,比如下载操作
static int Test(int i, string str)
{
Console.WriteLine("test:" + i + str);
Thread.Sleep(100);//让当亲线程休眠(暂停线程的执行) 单位ms
return 100;
}
static void Main(string[] args)
{//在main线程中执行 一个线程里面语句的执行 是从上到下的
// 通过委托 开启一个线程
Func<int, string, int> a = Test;
IAsyncResult ar = a.BeginI