zoukankan      html  css  js  c++  java
  • BeginInvoke()使用

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Xml;
    using System.Threading;
     
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("Client application is starting!");
                Thread.CurrentThread.Name = "Main Thread";
                Cal cal = new Cal();
                AddDelegate del = new AddDelegate(cal.Add);
     
                // 需要保存 IAsyncResult 对象以便后边条用EndInvoke方法时作参数传递
                IAsyncResult asyncResult = del.BeginInvoke(5, 6, null, null);
     
                // 做某些其它的事情,模拟需要执行 3 秒钟
                for (int i = 1; i <= 3; i++)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(i));
                    Console.WriteLine("{0}: Client executed {1} second(s).", Thread.CurrentThread.Name, i);
                }
     
                // 传递 IAsyncResult 对象
                int rtnVal = del.EndInvoke(asyncResult);
                Console.WriteLine("Result: {0}
    ", rtnVal);
     
                Console.WriteLine("
    Press any key to exit...");
                Console.ReadLine();
     
            }
     
            public delegate int AddDelegate(int a, int b);
     
            public class Cal
            {
                public int Add(int a, int b)
                {
                    if (Thread.CurrentThread.IsThreadPoolThread)
                    {
                        Thread.CurrentThread.Name = "Pool Thread";
                    }
                    Console.WriteLine("Method invoked!");
     
                    // 做某些其它的事情,模拟需要执行 2 秒钟
                    for (int i = 0; i < 2; i++)
                    {
                        Thread.Sleep(TimeSpan.FromSeconds(1));
                        Console.WriteLine("{0}: Add executed {1} second(s).", Thread.CurrentThread.Name, i);
                    }
                    Console.WriteLine("Method complete!");
                    return a + b;
                }
            }
        }
    }
  • 相关阅读:
    SQL Server 阻止了对组件 'Ole Automation Procedures' 的 过程'sys.sp_OACreate' 的访问
    谷歌浏览器扩展程序manifest.json参数详解
    获取天气api
    UVA 10385 Duathlon
    UVA 10668 Expanding Rods
    UVALIVE 3891 The Teacher's Side of Math
    UVA 11149 Power of Matrix
    UVA 10655 Contemplation! Algebra
    UVA 11210 Chinese Mahjong
    UVA 11384 Help is needed for Dexter
  • 原文地址:https://www.cnblogs.com/YzpJason/p/6852822.html
Copyright © 2011-2022 走看看