Func和Action的用法
个人学习总结:
Action< T >的用法 (同步)
class Program
{
//Action<T>的用法
static void Main(string[] args)
{
Action<string> FoodAction = new Action<string>(Food);
FoodAction("鱼香肉丝");
Console.ReadKey();
}
public static void Food(string foodName)
{
Console.WriteLine("我出去吃了{0}",foodName);
}
};
Action< T1, T2>的用法
class Program
{
static void Main(string[] args)
{
//Action< T1, T2>
Action<string,string> FoodAction = new Action<string,string>(Food);
FoodAction("鱼香肉丝","张三餐馆");
Console.WriteLine("王四也来吃饭了");
Console.ReadKey();
}
public static void Food(string foodName,string restaurant)
{
// Thread.Sleep(5000);
Console.WriteLine("张三出去吃了{0},在{1}吃的饭",foodName,restaurant);
}
}
Control.Invoke 方法 (Delegate) :在拥有此控件的基础窗口句柄的线程上执行指定的委托。
Control.BeginInvoke 方法 (Delegate) :在创建控件的基础句柄所在线程上异步执行指定委托。
运行后生成顺序:
张三出去吃了鱼香肉丝,在张三餐馆吃的饭
王四也来吃饭了
class Program
{
static void Main(string[] args)
{
//Action< T1, T2>
Action<string,string> FoodAction = new Action<string,string>(Food);
FoodAction.BeginInvoke("鱼香肉丝","张三餐馆",null,null);
Console.WriteLine("王四也来吃饭了");
Console.ReadKey();
}
public static void Food(string foodName,string restaurant)
{
Thread.Sleep(5000);
Console.WriteLine("张三出去吃了{0},在{1}吃的饭",foodName,restaurant);
}
}
直接写在函数体内
static void Main(string[] args)
{
Action<string, string> FoodAction = (string a, string b) =>
{
Thread.Sleep(5000);
Console.WriteLine("张三出去吃了{0},在{1}吃的饭", a, b);
};
FoodAction.BeginInvoke("鱼香肉丝", "张三餐馆", null, null);
Console.WriteLine("王四也来吃饭了");
Console.ReadKey();
}
运行后生成顺序:
王四也来吃饭了
张三出去吃了鱼香肉丝,在张三餐馆吃的饭
class Program
{
public string Name { get; set; }
public string FoodName { get; set; }
public string Restaurant { get; set; }
static void Main(string[] args)
{
Action<string, string> FoodAction = new Action<string, string>(Food);
//第一个是AsyncCallback委托是异步完成的回调方法。第二个是用户自定义对象,该对象将传递到回调方法中。
//BeginInvoke返回IAsyncResult接口,可用于检测异步调用的过程。
AsyncCallback call = new AsyncCallback(Food2);
Program pro = new Program();
pro.FoodName = "红烧茄子";
pro.Restaurant = "六麻子饭店";
FoodAction.BeginInvoke("鱼香肉丝","张三餐馆" ,call, pro);
Console.WriteLine("王四也来吃饭了");
Console.ReadKey();
}
public static void Food(string foodName, string restaurant)
{
Thread.Sleep(1000);
Console.WriteLine("张三出去吃了{0},在{1}吃的饭", foodName, restaurant);
}
public static void Food2(IAsyncResult ar)
{
Program pro = (Program)ar.AsyncState;
//Thread.Sleep(1000);
Console.WriteLine("六麻子出去吃了{0},在{1}吃的饭",pro.FoodName,pro.Restaurant);
}
}
运行后生成顺序:
王四也来吃饭了
张三出去吃了鱼香肉丝,在张三餐馆吃的饭
六麻子出去吃了红烧茄子,在六麻子饭店吃的饭
static void Main(string[] args)
{
Func<string> FoodFunc = new Func<string>(Food);
Console.WriteLine(FoodFunc());
Console.WriteLine("赵四也来吃饭了");
Console.ReadKey();
}
public static string Food()
{
Thread.Sleep(3000);
return ("鱼香肉丝");
}
运行后生成顺序:
鱼香肉丝
赵四也来吃饭了