C calls method instances synchronously and asynchronously
- 2020-05-24 06:00:58
- OfStack
namespace ConsoleTest
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("******** Synchronous call start **********");
int result = Add(1,2);
Console.WriteLine(" The synchronous call is completed, and the execution result is :" + result);
Console.WriteLine("******** Asynchronous call start **********");
SynAdd(1, 2, (r) => {
Console.WriteLine(" The asynchronous call is completed, and the result of execution is :" + r);
});
Console.WriteLine("------- Finished! ----------");
Console.ReadLine();
}
/// <summary>
/// Synchronized methods
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
static int Add(int a, int b)
{
Thread.Sleep(5000);
return a + b;
}
/// <summary>
/// The asynchronous call
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="callback"> Delegate object </param>
static void SynAdd(int a, int b, Action<int> callback)
{
Func<int> func = () =>
{
Thread.Sleep(5000);
return a+b;
};// Declare an asynchronous method implementation
func.BeginInvoke((ar) =>
{
var result = func.EndInvoke(ar);// The result of the execution of the call
callback.Invoke(result);// Delegate execution and return the result value
}, null);
}
}
}