Func Action asynchronous call
Action (no return value)
Directly on the code is very simple
AsyncCallback defines the callback function
IAsyncResult is the return value of begininvoke as the only parameter of AsyncCallback
action.BeginInvoke ("test", asyncCallback, "OK"); // ok is the value of AsyncState in the callback parameter
action.BeginInvoke ("test", null, null); // so there is no callback
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 (with return value)
func.EndInvoke ((o)) // o is isAsyncResult must end to have a return value
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)}"); //可以独立输出
}
Commonly called functions
public static void DoLong(string ss)
{
for (int i = 0; i < 100000; i++)
{
//Thread.Sleep(100);
i++;
}
Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId.ToString()},{ss}");
}
Main thread call
class Program
{
static void Main(string[] args)
{
Test test=new Test();
test.Actionstart();
test.FuncStart();
while (true)
{
}
}
}
result