using System;
using System.Runtime.Remoting.Messaging;
using System.Threading;
//回调模式
delegate long MyDel(int first, int second);
class Program
{
static long Sum(int x, int y)
{
Console.WriteLine(" Inside Sum");
Thread.Sleep(1111);
return x + y;
}
static void CallWhenDone(IAsyncResult iar)
{
Console.WriteLine(" Inside CallWhenDone");
AsyncResult ar = (AsyncResult)iar;
MyDel del = (MyDel)ar.AsyncDelegate;
long result = del.EndInvoke(iar);
Console.WriteLine($"End of the Invoke {result}");
}
static void Main()
{
MyDel del = new MyDel(Sum);
Console.WriteLine("Before BeginInvoke");
IAsyncResult iar = del.BeginInvoke(222, 3, new AsyncCallback(CallWhenDone), null);
Console.WriteLine("Doing more Work in Main");
Thread.Sleep(1121);
Console.WriteLine("Done with Main");
Console.Read();
}
}
using System;
using System.Threading;
//wait until done
delegate long MyDel(int first, int second);
class Program
{
static long Sum(int x, int y)
{
Console.WriteLine(" Inside Sum.");
Thread.Sleep(199);
return x + y;
}
static void Main()
{
MyDel myDel = new MyDel(Sum);
Console.WriteLine("Before BeginInvoked");
IAsyncResult asyncResult = myDel.BeginInvoke(11, 111, null, null);
Console.WriteLine("End BeginInvoked");
Console.WriteLine("Doing Stuff");
long result = myDel.EndInvoke(asyncResult);
Console.WriteLine(
$"After EndInvoked...{result}");
Console.Read();
}
}
using System;
using System.Threading;
namespace ConsoleApp1
{
//轮询方式
delegate long MyDel(int first, int second);
class Program
{
static long Sum(int x, int y)
{
Console.WriteLine(" Inside Sum");
Thread.Sleep(1000);
return x + y;
}
static void Main(string[] args)
{
MyDel myDel = new MyDel(Sum);
IAsyncResult asyncResult = myDel.BeginInvoke(222, 222, null, null);
Console.WriteLine("After BeginInvoke");
while (!asyncResult.IsCompleted)
{
Console.WriteLine("Not Dobe");
for (long i = 0; i < 100000; i++)
{
;
}
}
Console.WriteLine("Done");
long result = myDel.EndInvoke(asyncResult);
Console.WriteLine($"The Result is -----{result}");
Console.Read();
}
}
}