I created a WinForm test project: The interface is as follows:
Set up:
Here's the code:
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Threading;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;namespaceasynccallbackdemo{ Public Partial classForm1:form { PublicForm1 () {InitializeComponent (); Objmycal=ExecuteTask; } //define a delegate Public Delegate intMycalculator (intNumintms); //based on the delegate definition method, returns the square of a number Private intExecuteTask (intNumintms) {Thread.Sleep (MS); returnNum *num; } mycalculator objmycal=NULL; Private voidButton1_Click (Objectsender, EventArgs e) { for(inti =0; I < One; i++) { //defining the callback function Mycallback, passing in the callback value IObjmycal.begininvoke (TenI +*1, Mycallback, i); } } Private voidmycallback (IAsyncResult result) {//return Results intres =Objmycal.endinvoke (Result); Console.WriteLine ("{ 0} evaluates to {1}", result. Asyncstate.tostring (), res); } }}
A small example of a delegate-based C # asynchronous programming with an example of a callback function