SoFunction
Updated on 2025-03-01

The benefits and methods of C# asynchronous calls


//First prepare, asynchronous method (can be asynchronous, preferably not many threads)
privatestringMethodName(intNum,outintNum2)
{
Num2=Num;
return"HelloWorld";
}
//Program Endpoint
// When asynchronous completion, the method (callback method) is executed. This method can only have one parameter IAsyncResult, but this parameter is almost versatile and can pass object
privatevoidCallBackMethod(IAsyncResultar)
{
//Fetch the delegate object from the asynchronous state
DelegateNamedn=(DelegateName);
//Output parameters
inti;
//Be sure to EndInvoke, otherwise your fate will be miserable
stringr=(outi,ar);
("Asynchronously completed! The value of i is "()", and the value of r is "r);
}
//Define the delegate signed with the same signature as the method
privatedelegatestringDelegateName(intNum,outintNum2);
//Program portal
privatevoidRun()
{
//Instantiate the delegation and initially assign the value
DelegateNamedn=newDelegateName(MethodName);
//Output parameters
inti;
//Instantiated callback method
//You will understand that if you think of AsyncCallback as a Delegate, in fact, AsyncCallback is a special Delegate, just like an Event
AsyncCallbackacb=newAsyncCallback(CallBackMethod);
//Asynchronous start
//If the parameter acb is replaced with null, it means there is no callback method
//The last parameter dn can be replaced with any object. The object can be obtained from the parameters by the callback method, and it can be written as null. The parameter dn is equivalent to the ID of the thread. If there are multiple asynchronous threads, it can all be null, but it must not be the same, it cannot be the same object, otherwise it will be exception.
IAsyncResultiar=(1,outi,acb,dn);
//Go to do something else
//…………
}
//The final result should be: i=1, r="HelloWorld"
//In addition, if possible, you can choose not to use too much modification when defining the delegation:
///<summary>
///Define the delegation
///</summary>
///<returns></returns>
publicdelegateboolAsyncdelegate();
///<summary>
///Callbackmethodmusthavethesamesignatureasthe
///AsyncCallbackdelegate
///</summary>
///<paramname="ar"></param>
privatevoidCallbackMethod(IAsyncResultar)
{
//Retrievethedelegate.
Asyncdelegatedlgt=(Asyncdelegate);
//CallEndInvoketoretrievetheresults.
(ar);
}
//Called in other methods:
//Asynchronous execution
//Specify the delegate method
Asyncdelegateisgt=newAsyncdelegate();
IAsyncResultar=(newAsyncCallback(CallbackMethod),isgt);