1.简单线程实例 以及委托(同步委托、异步委托)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Runtime.Remoting.Messaging;
namespace ThreadTest
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("主线程运行中.....{0}",Thread.CurrentThread.ManagedThreadId);
#region 线程
Thread thread = new Thread(new ThreadStart(ShowMsg));
//只是 建议操作系统把当前线程当成 低级别
thread.Priority = ThreadPriority.Lowest;
//给开发人员用,来识别不同系统
thread.Name = "threadtest";
//后台线程:如果所有的前台线程都退出了,那么后台线程自动关闭
thread.IsBackground = true;
//并没有执行,告诉操作系统
thread.Start();
//关闭线程
//thread.Abort();
#endregion
/*
#region 异步委托
AddDel addDel = new AddDel(Add);
int result = 0;
//同步调用,当前线程去调用
//int result = addDel(1, 2);
//第一种:回调函数
//启动委托指向的方法执行,具体有线程池提供一个线程来执行当前的委托执行的方法
//IAsyncResult asynResult = addDel.BeginInvoke(1, 2, null, null);
//此EndInvoke方法会阻塞当前线程,直到委托方法执行完毕后,并将返回值交result后,继续执行后面代码
//int result = addDel.EndInvoke(asynResult);
//第二种:使用回调函数
IAsyncResult ascResult = addDel.BeginInvoke(1, 2, new AsyncCallback(MyDelCallBack), 33);
//Console.WriteLine("result:{0}", result);
#endregion
**/
Console.WriteLine("主线程执行完成...");
Console.ReadKey();
}
public delegate int AddDel(int a, int b);
public static int Add(int a,int b)
{
Console.WriteLine("工作线程工作着....{0}",Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(3000);
return a+b;
}
//异步委托 执行完成了的回调函数
public static void MyDelCallBack(IAsyncResult asyResult)
{
//将接口类型转换成实例类型
AsyncResult aResult = (AsyncResult)asyResult;
//判断委托是否执行完成
while(!aResult.IsCompleted)
{
//主线程干些时间
//防止主线程阻塞
}
//转换成我们自己的委托类型
AddDel addDelResult = (AddDel)aResult.AsyncDelegate;
//获取回调状态值
int state = (int)aResult.AsyncState;
//执行完成获取 执行的结果
int result = addDelResult.EndInvoke(asyResult);
Console.WriteLine("异步完成的回调方法执行的结果:{0}----回调状态:{1}----线程id:{2}",result,state,Thread.CurrentThread.ManagedThreadId);
}
static void ShowMsg()
{
Console.WriteLine("ShowMsg方法----工作线程工作着....{0}",Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(1000);
}
}
}