delegate void textAsy(); static void Main(string[] args) { textAsy t = texts; AsyncCallback callBack = new AsyncCallback(sendCallBack); t.BeginInvoke(callBack, new { timeNow= DateTime.Now.Ticks,timeStr=DateTime.Now.ToString() }); Console.WriteLine(DateTime.Now); Console.Read(); } public static void texts() { Thread.Sleep(1100); Console.WriteLine(DateTime.Now); } //3)在回调函数中使用StateObject private static void sendCallBack(IAsyncResult ar) { Console.WriteLine("异步状态" + ((dynamic)ar.AsyncState).timeNow + ((dynamic)ar.AsyncState).timeStr); }
由于操作是异步的 我们不知道他什么时候完成 所以一般采用回调函数处理
delegate void textAsy(); static void Main(string[] args) { textAsy t = texts; AsyncCallback callBack = new AsyncCallback(sendCallBack); t.BeginInvoke(callBack,DateTime.Now.Ticks); Console.WriteLine(DateTime.Now); Console.Read(); } public static void texts() { Thread.Sleep(1100); Console.WriteLine(DateTime.Now); } //3)在回调函数中使用StateObject private static void sendCallBack(IAsyncResult ar) { Console.WriteLine("异步状态"+(long)ar.AsyncState); }
ar.AsyncState 就是 t.BeginInvoke(callBack,DateTime.Now.Ticks);中的参数
delegate void textAsy(); static void Main(string[] args) { textAsy t = texts; AsyncCallback callBack = new AsyncCallback(sendCallBack); t.BeginInvoke(callBack, new { timeNow= DateTime.Now.Ticks,timeStr=DateTime.Now.ToString() }); Console.WriteLine(DateTime.Now); Console.Read(); } public static void texts() { Thread.Sleep(1100); Console.WriteLine(DateTime.Now); } //3)在回调函数中使用StateObject private static void sendCallBack(IAsyncResult ar) { Console.WriteLine("异步状态" + ((dynamic)ar.AsyncState).timeNow + ((dynamic)ar.AsyncState).timeStr); }