Csharp/C Sharp/Development Class/IAsyncResult — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Текущая версия на 11:43, 26 мая 2010

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");
    }
}