委托异步是否是多线程?

public delegate int SumDelegate(int i,int j);

public class AsyncDelegate
    {
        private const int MILLISECONDS = 0X32;
        public int Sum(int i, int j)
        {
            Console.WriteLine("委托异步:当前线程 ID:{0}\n是否属于当前托管线程池:{1}\n线程优先级:{2}\n线程状态:{3}",
                    System.Threading.Thread.CurrentThread.ManagedThreadId,
                    (System.Threading.Thread.CurrentThread.IsThreadPoolThread ? " 是 " : " 否 "),
                    System.Threading.Thread.CurrentThread.Priority,
                    System.Threading.Thread.CurrentThread.ThreadState + "\n");
            return i + j;
        }
        public int AsyncSum(int i, int j)
        {
            SumDelegate fn = new SumDelegate(Sum);
            IAsyncResult ar = fn.BeginInvoke(i, j, null, fn);
            while (true) {
                if (ar.AsyncWaitHandle.WaitOne(MILLISECONDS, false))
                {
                    Console.WriteLine("主线程运行:当前线程 ID:{0}\n是否属于当前托管线程池:{1}\n线程优先级:{2} \n线程状态:{3}",
                        System.Threading.Thread.CurrentThread.ManagedThreadId,
                        (System.Threading.Thread.CurrentThread.IsThreadPoolThread ? " 是 " : " 否 "),
                        System.Threading.Thread.CurrentThread.Priority,
                        System.Threading.Thread.CurrentThread.ThreadState + "\n");
                    break;
                }
            }
            return fn.EndInvoke(ar);
        }
    }

class Program
    {
        static void Main(string[] args)
        {
            AsyncDelegate async = new AsyncDelegate();
            for (int i = 0; i < 2; i++) {
                async.AsyncSum(i, i + 1);
            }
        }
    }

运行结果:

委托异步是否是多线程?_第1张图片

你可能感兴趣的:(多线程)