Delegate BeginInvoke and EndInvoke methods are the fundatmental of c# asynchronous programming. here is a example:
public class AsyncResultPatternIntroduction {
delegate void WorkerThreadHandler();
public void AsyncMain() {
WorkerThreadHandler workerMethod = null;
IAsyncResult asyncResult = null;
workerMethod = new WorkerThreadHandler(DoWork);
Console.WriteLine("Starting app...");
asyncResult = workerMethod.BeginInvoke(null, null);
while (!asyncResult.IsCompleted) {
Console.Write(".");
Thread.Sleep(100);
}
workerMethod.EndInvoke(asyncResult);
Console.WriteLine("Ending app...");
}
public void DoWork() {
Console.WriteLine("\nDoWork() started...");
Thread.Sleep(1000);
Console.WriteLine("\nDoWork() ending...");
}
}
To create an class with BeginXXX and EndXXX methods: here is a example:
public class Sum {
internal delegate UInt64 SumDelegate(UInt64 n);
SumDelegate sumDelegate = null;
public Sum() {
sumDelegate = CalculateSum;
}
public IAsyncResult BeginCalculateSum(UInt64 n,
AsyncCallback callback,
object state) {
return sumDelegate.BeginInvoke(n, callback, state);
}
public UInt64 EndCalculateSum(IAsyncResult result) {
return sumDelegate.EndInvoke(result);
}
public UInt64 CalculateSum(UInt64 n) {
UInt64 sum = 0;
for (UInt64 i = 1; i <= n; i++) {
checked {
// I use checked code so that an OverflowException gets
// thrown if the sum doesn't fit in a UInt64.
sum += i;
}
}
Thread.Sleep(1000);
return sum;
}
}
2fbf85e0-3851-48b9-95a5-2c49426e5939|0|.0
DotNet