Ejemplo n.º 1
0
        /// <summary>
        /// 等待句柄
        /// </summary>
        public void Method2()
        {
            TakesAWhileDelegate d = TakesAWhile;
            var ar = d.BeginInvoke(1, 2000, null, null);

            var i = 0;

            while (true)
            {
                Console.Write(++i);
                //设置等待最长时间
                //使用AsyncWaitHandle返回一个WaitHandle句柄,他可以等待线程完成其任务
                //第一个参数为等待时间
                //第二个参数,如果等待之前先退出上下文的同步域(如果在同步上下文中),并在稍后重新获取它,则为 true;否则为 false。
                if (ar.AsyncWaitHandle.WaitOne(50, false))
                {
                    Console.WriteLine("Can get the result now");
                    break;
                }
            }

            var result = d.EndInvoke(ar);

            Console.WriteLine($"result:{result}");
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 使用回调方法,必须注意这个方法从委托线程中调用,而不是从主线程中调用
        /// BeginInvoke的第三个参数就是异步回调函数,这个函数的类型就是如下写的一样
        /// 最后一个参数,可以是任意对象,从回调方法中访问它
        /// </summary>
        /// <param name="args"></param>
        static void MainDel3(string[] args)
        {
            TakesAWhileDelegate dl = TakesAWhile;

            dl.BeginInvoke(1, 3000, TakesAWhileCompleted, dl);
            for (int i = 0; i < 100; i++)
            {
                Console.Write(".");
                Thread.Sleep(50);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 异步回调,除了单独定义一个方法,并给它传递BeginInvoke()方法之外,Lambda表达式也非常适合这种情况
        /// </summary>
        public void Method3()
        {
            TakesAWhileDelegate dl = TakesAWhile;
            IAsyncResult        ar = dl.BeginInvoke(1, 3000, TakesAWhileCompleted, dl);

            for (int i = 0; i < 100; i++)
            {
                Console.Write(".");
                Thread.Sleep(50);
            }
        }
Ejemplo n.º 4
0
        static void Main()
        {
            // synchronous
            // TakesAWhile(1, 3000);
            TakesAWhileDelegate d1 = TakesAWhile;

            // polling
            //IAsyncResult ar = d1.BeginInvoke(1, 3000, null, null);
            //while (!ar.IsCompleted)
            //{
            //   // doing something else
            //   Console.Write(".");
            //   Thread.Sleep(50);
            //}
            //int result = d1.EndInvoke(ar);
            //Console.WriteLine("result: {0}", result);

            // wait handle
            //IAsyncResult ar = d1.BeginInvoke(1, 3000, null, null);
            //while (true)
            //{
            //   Console.Write(".");
            //   if (ar.AsyncWaitHandle.WaitOne(50, false))
            //   {
            //      Console.WriteLine("Can get the result now");
            //      break;
            //   }
            //}
            //int result = d1.EndInvoke(ar);
            //Console.WriteLine("result: {0}", result);

            // async callback
            //d1.BeginInvoke(1, 3000, TakesAWhileCompleted, d1);
            //for (int i = 0; i < 100; i++)
            //{
            //   Console.Write(".");
            //   Thread.Sleep(50);
            //}

            d1.BeginInvoke(1, 3000,
                           ar =>
            {
                int result = d1.EndInvoke(ar);
                Console.WriteLine("result: {0}", result);
            },
                           null);
            for (int i = 0; i < 100; i++)
            {
                Console.Write(".");
                Thread.Sleep(50);
            }
            Console.ReadKey();
        }
    static void Main()
    {
        // asynchronous by using a delegate
        TakesAWhileDelegate dl = TakesAWhile;

        dl.BeginInvoke(1, 5000, TakesAWhileCompleted, dl);

        for (int i = 0; i < 200; i++)
        {
            Console.Write(".");
            Thread.Sleep(50);
        }
    }
Ejemplo n.º 6
0
        private static void TakesAWhileCompleted(IAsyncResult ar)
        {
            if (ar == null)
            {
                throw new ArgumentNullException("ar");
            }
            TakesAWhileDelegate dl = ar.AsyncState as TakesAWhileDelegate;

            Trace.Assert(dl != null, "Invalid object type");
            int result = dl.EndInvoke(ar);

            Console.WriteLine("result:{0}", result);
        }
Ejemplo n.º 7
0
        public void RunEndInvoke()
        {
            TakesAWhileDelegate dl = new TakesAWhileDelegate(TakesAWhile);
            IAsyncResult        ar = dl.BeginInvoke(5, 3000, null, null);
            int result             = 0;

            while (!ar.IsCompleted)//判断委托函数结束 || ar.AsyncWaitHandle.WaitOne(100,false)
            {
                Console.Write("*");
                Thread.Sleep(100);
            }
            result = dl.EndInvoke(ar);
            Console.WriteLine(string.Format("Result: {0}", result));
        }
Ejemplo n.º 8
0
        /// <summary>
        /// 投票
        /// </summary>
        public void Method1()
        {
            TakesAWhileDelegate d  = TakesAWhile;
            IAsyncResult        ar = d.BeginInvoke(1, 3000, null, null);

            while (!ar.IsCompleted)
            {
                Console.WriteLine(".");
                Thread.Sleep(50);
            }
            int result = d.EndInvoke(ar);

            Console.WriteLine("Result is: {0}", result);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// 异步回调
        /// BeginInvoke代表开始调用,返回一个代表异步结果的对象(IAsyncResult)
        /// EndInvoke代表结束调用,返回调用函数结果
        /// </summary>
        public void Method3()
        {
            //BeginInvoke总是会带AsyncCallback和object参数
            //AsyncCallback会在线程结束时调用,object代表用户自定义对象,该对象将传递到回调方法中,也就是AsyncState
            //AsyncCallback可以用lambda表达式代替,并不需要传递第四个参数可以直接进行使用
            TakesAWhileDelegate d = TakesAWhile;
            var ar1 = d.BeginInvoke(1, 2000, TakesAWhileComleted, d);

            /*var ar2 = d.BeginInvoke(1, 2000, ar =>
             * {
             *  var result = d.EndInvoke(ar);
             *  Console.WriteLine($"TreadId:{Thread.CurrentThread.ManagedThreadId}");
             * }, null);*/
        }
Ejemplo n.º 10
0
        public void Method4()
        {
            TakesAWhileDelegate dl = TakesAWhile;
            IAsyncResult        ar = dl.BeginInvoke(1, 3000, p =>
            {
                int result = dl.EndInvoke(p);
                Console.WriteLine("Result is: {0}", result);
            }, dl);

            for (int i = 0; i < 100; i++)
            {
                Console.Write(".");
                Thread.Sleep(50);
            }
        }
Ejemplo n.º 11
0
        static void Main()
        {
            TakesAWhileDelegate dl = TakesAWhile;

            var ar = dl.BeginInvoke(1, 3000, null, null);

            while (!ar.IsCompleted)
            {
                Console.Write(".");
                Thread.Sleep(50);
            }

            var result = dl.EndInvoke(ar);

            Console.WriteLine("result: {0}", result);
        }
Ejemplo n.º 12
0
        /*这几个方法都是委托的异步实现,即在主线程中判断委托是否执行完,若完成则继续主线程下面的方法*/

        static void MainDel(string[] args)
        {
            TakesAWhileDelegate dl = TakesAWhile;
            //BeginInvoke调用委托方法,并且可以传递委托的两个参数,且返回一个IAsyncResult类型的变量,带有有效信息
            IAsyncResult ar = dl.BeginInvoke(1, 3000, null, null);

            while (!ar.IsCompleted)
            {
                //doing something else in the main thread
                Console.Write(".");
                Thread.Sleep(50);
            }
            int result = dl.EndInvoke(ar);

            Console.WriteLine("result:{0}", result);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// 投票
        /// </summary>
        public void Method1()
        {
            TakesAWhileDelegate d = TakesAWhile;

            var ar = d.BeginInvoke(1, 2000, null, null);

            //isCompleted异步线程是否运行结束
            while (!ar.IsCompleted)
            {
                Console.Write(".");
                Thread.Sleep(50);
            }
            var result = d.EndInvoke(ar);

            Console.WriteLine($"result:{result}");
        }
Ejemplo n.º 14
0
        /// <summary>
        /// 等待句柄
        /// </summary>
        public void Method2()
        {
            TakesAWhileDelegate d  = TakesAWhile;
            IAsyncResult        ar = d.BeginInvoke(1, 3000, null, null);

            while (true)
            {
                if (ar.AsyncWaitHandle.WaitOne(50, false))
                {
                    Console.WriteLine("Can get the result..");
                    break;
                }
            }
            int result = d.EndInvoke(ar);

            Console.WriteLine("Result is: {0}", result);
        }
    static void Main()
    {
        TakesAWhileDelegate dl = TakesAWhile;

        dl.BeginInvoke(1, 5000,
                       ar => {
            int result = dl.EndInvoke(ar);
            Console.WriteLine("result: {0}", result);
        }, dl
                       );

        for (int i = 0; i < 200; i++)
        {
            Console.Write(".");
            Thread.Sleep(50);
        }
    }
Ejemplo n.º 16
0
        /*
         *使用lambda来简化代码
         *这里使用的参数ar,就是回调函数规定的参数,省去了声明。
         */
        static void MainDel3_lambda(string[] args)
        {
            TakesAWhileDelegate dl = TakesAWhile;

            dl.BeginInvoke(1, 3000,
                           ar =>
            {
                int result = dl.EndInvoke(ar);
                Console.WriteLine("result:{0}", result);
            },
                           null);
            for (int i = 0; i < 100; i++)
            {
                Console.Write(".");
                Thread.Sleep(50);
            }
        }
Ejemplo n.º 17
0
        public static void Run()
        {
            TakesAWhileDelegate d1 = TakesAWhile;
            IAsyncResult        ar = d1.BeginInvoke(1, 3000, null, null);

            while (true)
            {
                if (ar.AsyncWaitHandle.WaitOne(50))
                {
                    Console.WriteLine("Can get the result now");
                    break;
                }
            }
            int result = d1.EndInvoke(ar);

            Console.WriteLine("result:" + result);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// WaitHandle 是一个抽象基类,用于等待一个信号的设置。可以等待不同的信号,因为 WaitHandle 是一个基类,可以从中派生一些类。
        /// 在描述异步委托时,已经使用了 WaitHandle 基类。异步委托的 BeginInvoke() 方法返回一个实现了 IAsycResult 接口的对象。
        /// 使用 IAsycResult 接口,可以用 AsycWaitHandle 属性访问 WaitHandle 基类。
        /// 在调用 WaitOne() 方法时,线程会等待接收一个与等待句柄相关的信号。
        /// 使用 WaitHandle 基类可以等待一个信号的出现(WaitOne()方法)、等待必须发出信号的多个对象(WaitAll()方法)、或者等待多个对象中的一个(WaitAny()方法)。
        /// WaitAll() 和 WaitAny() 是 WaitHandle 类的静态方法,接收一个 WaitHandle 参数数组。
        /// WaitHandle 基类有一个 SafeWaitHandle 属性,其中可以将一个本机句柄赋予一个操作系统资源,并等待该句柄。
        /// 例如,可以指定一个 SafeFileHandle 等待文件 I/O 操作的完成,或者指定自定义的 SafeTransactionHandle。
        /// 因为Murex、EventWaitHandle 和 Semapbore 类派生自 WaitHandle 基类,所以可以在等待时使用它们。
        /// </summary>
        public void WaitHandleDemo()
        {
            TakesAWhileDelegate d1 = TakesAWhile;
            IAsyncResult        ar = d1.BeginInvoke(1, 3000, null, null);

            while (true)
            {
                Console.Write(".");
                if (ar.AsyncWaitHandle.WaitOne(50, false))
                {
                    Console.WriteLine("Can get the result now");
                    break;
                }
            }
            int result = d1.EndInvoke(ar);

            Console.WriteLine("result: {0}", result);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// 使用等待句柄来实现异步操作
        /// 同过AsyncWaitHandle可以访问到等待句柄
        /// </summary>
        /// <param name="args"></param>
        static void MaindDel2(string[] args)
        {
            TakesAWhileDelegate dl = TakesAWhile;
            IAsyncResult        ar = dl.BeginInvoke(1, 3000, null, null);

            while (true)
            {
                Console.Write(".");
                //WaitOne等待委托线程完成任务。设置等待时间50ms,如果50ms内没有接收到委托线程完成的结果超时返回false,继续while循环,若接到,则break结束循环。
                if (ar.AsyncWaitHandle.WaitOne(50))
                {
                    Console.WriteLine("Can get the result now");
                    break;
                }
            }
            int result = dl.EndInvoke(ar);

            Console.WriteLine("result:{0}", result);
        }
Ejemplo n.º 20
0
        static void Main()
        {
            TakesAWhileDelegate d1 = TakesAWhile;


            IAsyncResult ar = d1.BeginInvoke(1, 3000, null, null);

            while (true)
            {
                Write(".");
                if (ar.AsyncWaitHandle.WaitOne(50))
                {
                    WriteLine("Can get the result now");
                    break;
                }
            }
            int result = d1.EndInvoke(ar);

            WriteLine($"result: {result}");
        }
Ejemplo n.º 21
0
    static void Main()
    {
        // asynchronous by using a delegate
        TakesAWhileDelegate dl = TakesAWhile;

        IAsyncResult ar = dl.BeginInvoke(1, 5000, null, null);

        while (true)
        {
            Console.Write(".");
            if (ar.AsyncWaitHandle.WaitOne(50, false))
            {
                Console.WriteLine("Can get the result now");
                break;
            }
        }

        int result = dl.EndInvoke(ar);

        Console.WriteLine("result is {0}", result);
    }
    static void Main()
    {
        // 这样是同步调用没有任何意义
        // TakesAWhile(1, 3000);

        // 使用异步调用必须使用委托
        TakesAWhileDelegate dl = TakesAWhile;

        // 开始进行异步调用,如果异步线程未结束则打印一个小点,然后停顿50毫秒
        IAsyncResult ar = dl.BeginInvoke(1, 5000, null, null);

        while (!ar.IsCompleted)
        {
            // 这段内容是在主线程中执行的
            Console.Write(".");
            Thread.Sleep(50);
        }

        //
        int result = dl.EndInvoke(ar);

        Console.WriteLine("result is {0}", result);
    }
Ejemplo n.º 23
0
        static void Main()
        {
            try
            {
                TakesAWhileDelegate d1 = TakesAWhile;

                IAsyncResult ar = d1.BeginInvoke(1, 3000, null, null);
                while (true)
                {
                    Write(".");
                    if (ar.AsyncWaitHandle.WaitOne(50))
                    {
                        WriteLine("Can get the result now");
                        break;
                    }
                }
                int result = d1.EndInvoke(ar);
                WriteLine($"result: {result}");
            }
            catch (PlatformNotSupportedException)
            {
                WriteLine("PlatformNotSupported exception - with async delegates please use the full .NET Framework");
            }
        }
Ejemplo n.º 24
0
        public static void AsyncDelegateDemoStart()
        {
            try
            {
                TakesAWhileDelegate d1 = TakesAWhile;

                IAsyncResult ar = d1.BeginInvoke(1, 3000, null, null);
                while (true)
                {
                    Console.Write(".");
                    if (ar.AsyncWaitHandle.WaitOne(50))
                    {
                        Console.WriteLine("现在不能返回结果");
                        break;
                    }
                }
                int result = d1.EndInvoke(ar);
                Console.WriteLine($"结果: {result}");
            }
            catch (PlatformNotSupportedException)
            {
                Console.WriteLine("PlatformNotSupported exception - with async delegates please use the full .NET Framework");
            }
        }
Ejemplo n.º 25
0
        static void Main(string[] args)
        {
            // synchronous method call
            // TakesAWhile(1,3000);

            // asynchronous by using a delegate
            TakesAWhileDelegate dl = TakesAWhile;

            dl.BeginInvoke(1, 500, TakesAWhileCompleted, dl);
            for (int i = 0; i < 100; i++)
            {
                Console.Write(".");
                Thread.Sleep(50);
            }

            /**
             * IAsyncResult ar = dl.BeginInvoke(1, 500, null, null);
             * /**
             * 投票
             * while (!ar.IsCompleted)
             * {
             *  // doing something else in the main thread
             *  Console.Write(".");
             *  Thread.Sleep(50);
             * }*/

            /**
             * 等待句柄
             * while (true)
             * {
             *  Console.Write(".");
             *  if (ar.AsyncWaitHandle.WaitOne(50, false))
             *  {
             *      Console.WriteLine("Can get the result now");
             *      break;
             *  }
             * }*/

            /**
             * 投票/等待句柄
             * int result = dl.EndInvoke(ar);
             * Console.WriteLine("result:{0}", result);*/

            /**
             * Thread 创建线程
             * var t1 = new Thread(ThreadMain) { Name = "MyNewThread", IsBackground = false };
             * t1.Start();
             * Console.WriteLine("Main thread ending now.");
             */

            /**
             * ThreadPool 线程池创建
             * int nWorkerThreads;
             * int nCompletionPortThreads;
             * ThreadPool.GetMaxThreads(out nWorkerThreads, out nCompletionPortThreads);
             * Console.WriteLine("Max worker threads:{0},I/O completion threads:{1}",
             *  nWorkerThreads, nCompletionPortThreads);
             * for (int i = 0; i < 5; i++)
             * {
             *  ThreadPool.QueueUserWorkItem(JobForAThread);
             * }
             */

            //using task factory
            TaskFactory tf = new TaskFactory();
            Task        t1 = tf.StartNew(TaskMethod);

            //using the task factory via a task
            Task t2 = Task.Factory.StartNew(TaskMethod);

            //using Task constructor
            Task t3 = new Task(TaskMethod);

            t3.Start();

            Task t4 = new Task(TaskMethod, TaskCreationOptions.PreferFairness);

            t4.Start();

            Console.ReadLine();
        }
Ejemplo n.º 26
0
        public void GetHost()
        {
            if (data.data_version != data_version)
            {
                data.Reset();
            }
            TakesAWhileDelegate dl_SB = GHT_SB;
            IAsyncResult        ar_SB = dl_SB.BeginInvoke(null, null);
            TakesAWhileDelegate dl_SU = GHT_SU;
            IAsyncResult        ar_SU = dl_SU.BeginInvoke(null, null);
            TakesAWhileDelegate dl_I  = GHT_I;
            IAsyncResult        ar_I  = dl_I.BeginInvoke(null, null);
            TakesAWhileDelegate dl_9  = GHT_9;
            IAsyncResult        ar_9  = dl_9.BeginInvoke(null, null);
            TakesAWhileDelegate dl_C  = GHT_C;
            IAsyncResult        ar_C  = dl_C.BeginInvoke(null, null);

            while (!(ar_SB.IsCompleted && ar_SU.IsCompleted && ar_I.IsCompleted && ar_9.IsCompleted && ar_C.IsCompleted))
            {
                Thread.Sleep(100);
            }
            data.SmartHost_Beijing_OK = dl_SB.EndInvoke(ar_SB);
            data.SmartHost_US_OK      = dl_SU.EndInvoke(ar_SU);
            data.imouto_host_OK       = dl_I.EndInvoke(ar_I);
            data.ninehost_OK          = dl_9.EndInvoke(ar_9);
            data.custom_OK            = dl_C.EndInvoke(ar_C);

            /* * update using thread.
             * try
             * {
             *  WebClient GetHost = new WebClient();
             *  GetHost.Credentials = CredentialCache.DefaultCredentials;
             *  Byte[] pageData = GetHost.DownloadData("https://smarthosts.googlecode.com/svn/trunk/hosts");
             *  string pageHtml = Encoding.Default.GetString(pageData);
             *  data.SmartHost_Beijing.Clear();
             *  data.SmartHost_Beijing = new List<string>(pageHtml.Split('\n'));
             *  Byte[] PageData2 = GetHost.DownloadData("https://smarthosts.googlecode.com/svn/trunk/hosts_us");
             *  string pageHtml2 = Encoding.Default.GetString(PageData2);
             *  data.SmartHost_US.Clear();
             *  data.SmartHost_US = new List<string>(pageHtml2.Split('\n'));
             *  Byte[] PageData3 = GetHost.DownloadData("https://imoutohost.googlecode.com/git/imouto.host.txt");
             *  string pageHtml3 = Encoding.Default.GetString(PageData3);
             *  data.imouto_host.Clear();
             *  data.imouto_host = new List<string>(pageHtml3.Split('\n'));
             *  Byte[] PageData4 = GetHost.DownloadData("http://moe9.tk/Xction/9Hosts/Static/Win");
             *  string pageHtml4 = Encoding.Default.GetString(PageData4);
             *  data.ninehost.Clear();
             *  data.ninehost = new List<string>(pageHtml4.Split('\n'));
             * }
             * catch (WebException)
             * {
             *  MessageBox.Show("Download Error,Check your network or Update the Software.");
             * }
             * */
            string downloaderror = "";

            if (!data.SmartHost_Beijing_OK)
            {
                downloaderror += "Smarthost_Beijing,";
            }
            if (!data.SmartHost_US_OK)
            {
                downloaderror += "Smarthost_US,";
            }
            if (!data.imouto_host_OK)
            {
                downloaderror += "Imouto host,";
            }
            if (!data.ninehost_OK)
            {
                downloaderror += "9host,";
            }
            if (!data.custom_OK)
            {
                downloaderror += "Custom host,";
            }
            if (!downloaderror.Equals(""))
            {
                MessageBox.Show(downloaderror + "Download Error. Some Host didn't Update. Check your Network or Update the Software.");
            }
            SaveLocalData();
        }//Download Host Data from SmartHost