C# asynchronous call uses delegate asynchronous call

Time:2022-5-10
1: Asynchronous call to callback free function
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading;
 
namespace UnitTestProject1
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
new AsynchronousTest().Test();
}
}
 
public class AsynchronousTest
{
///
///Step 1: create a delegate
///
///
///
///
public delegate int deletest(int a, int b);
///
///Step 2: Create method
///
///
///
///
public int Add(int a, int b)
{
Thread.Sleep(500);
return a + b;
}
///
///Step 3: call
///
public void Test()
{
var d = new deletest(Add);
IAsyncResult res = d.BeginInvoke(1, 2, null, null);
}
}
}
2: Asynchronous call with callback function
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading;
 
namespace UnitTestProject1
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
new AsynchronousTest().Test();
}
}
 
public class AsynchronousTest
{
///
///Step 1: create a delegate
///
///
///
///
public delegate int deletest(int a, int b);
///
///Step 2: Create method
///
///
///
///
public int Add(int a, int b)
{
Thread.Sleep(500);
return a + b;
}
///
///Callback function
///Note: only no return value is allowed
///Parameter can only be IAsyncResult
///
public void CallbackF(IAsyncResult result)
{
//The asyncdelegate property can be cast to the actual class of a user-defined delegate.
deletest test = (deletest)((System.Runtime.Remoting.Messaging.AsyncResult)result).AsyncDelegate;
var d = test. EndInvoke(result); // The return value of the called method add()
 
//Things to deal with
//…………….
}
///
///Step 3: call
///
public void Test()
{
var d = new deletest(Add);
//New asynccallback (callbackf) callback function
IAsyncResult res = d.BeginInvoke(1, 2, new AsyncCallback(CallbackF), null);
}
}
}