Func Action 异步调用
Action(无返回值)
直接上代码很简单的
AsyncCallback定义了回调函数
IAsyncResult 是begininvoke的返回值 作为AsyncCallback的唯一参数
action.BeginInvoke(“test”, asyncCallback, “OK”); //ok是回调参数中AsyncState的值
action.BeginInvoke(“test”, null, null); //这样就可以没有回调了
public void Actionstart()
{
Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId.ToString()}");
Action<string> action = DoLong;
AsyncCallback asyncCallback = (ar) => //完成的回调函数
{
Console.WriteLine(ar.AsyncState);
};
IAsyncResult asyncResult = action.BeginInvoke("test", asyncCallback, "OK");
asyncResult.AsyncWaitHandle.WaitOne(); //型号量
Console.WriteLine("全部结束!~");
}
Func(有返回值)
func.EndInvoke((o))//o是isAsyncResult 一定要end才有返回值
public void FuncStart()
{
Func<string, int> func = new Func<string, int>((o) => { return o.Length; });
IAsyncResult isAsyncResult= func.BeginInvoke("zhazha", (o) =>
{
Console.WriteLine($"结果输出:{func.EndInvoke((o))}"); //可以在回调中输出
Console.WriteLine("回调函数end");
},"test");
//Console.WriteLine($"结果输出:{func.EndInvoke(isAsyncResult)}"); //可以独立输出
}
共同调用的函数
public static void DoLong(string ss)
{
for (int i = 0; i < 100000; i++)
{
//Thread.Sleep(100);
i++;
}
Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId.ToString()},{ss}");
}
主线程调用
class Program
{
static void Main(string[] args)
{
Test test=new Test();
test.Actionstart();
test.FuncStart();
while (true)
{
}
}
}
结果