Csharp/C Sharp/Development Class/IAsyncResult
sample code for the EndInvoke method
using System;
using System.Threading;
public delegate int DelegateClass(out DateTime start,out DateTime stop);
public class Starter {
public static void Main() {
DelegateClass del = MethodA;
DateTime start;
DateTime stop;
IAsyncResult ar = del.BeginInvoke(out start, out stop,null, null);
ar.AsyncWaitHandle.WaitOne();
int elapse = del.EndInvoke(out start, out stop, ar);
Console.WriteLine("Start time: {0}", start.ToLongTimeString());
Console.WriteLine("Stop time: {0}", stop.ToLongTimeString());
Console.WriteLine("Elapse time: {0} seconds",elapse);
}
public static int MethodA(out DateTime start, out DateTime stop) {
start = DateTime.Now;
Thread.Sleep(5000);
stop = DateTime.Now;
return (stop - start).Seconds;
}
}
What happens if an unhandled exception is raised in a multicast delegate?
using System;
using System.Threading;
public delegate void DelegateClass();
public class Starter {
public static void Main() {
Console.WriteLine("Running on primary thread");
try {
DelegateClass del = MethodA;
IAsyncResult ar = del.BeginInvoke(null, null);
del.EndInvoke(ar);
} catch (Exception except) {
Console.WriteLine("Running on primary thread");
Console.WriteLine("Exception caught: " + except.Message);
}
}
public static void MethodA() {
if (Thread.CurrentThread.IsThreadPoolThread == true) {
Console.WriteLine("Running on a thread pool thread");
} else {
Console.WriteLine("Running on primary thread");
}
throw new Exception("failure");
}
}