zoukankan      html  css  js  c++  java
  • IAsyncResult 接口

    using System;
    using System.Threading;

    namespace Examples.AdvancedProgramming.AsynchronousOperations
    {
        public class AsyncDemo
        {
            // The method to be executed asynchronously.
            public string TestMethod(int callDuration, out int threadId)
            {
                Console.WriteLine("Test method begins.");
                Thread.Sleep(callDuration);
                threadId = Thread.CurrentThread.ManagedThreadId;
                return String.Format("My call time was {0}.", callDuration.ToString());
            }
        }
        // The delegate must have the same signature as the method
        // it will call asynchronously.
        public delegate string AsyncMethodCaller(int callDuration, out int threadId);
    }



    namespace Examples.AdvancedProgramming.AsynchronousOperations
    {
        public class AsyncMain
        {
            static void Main()
            {
                // The asynchronous method puts the thread id here.
                int threadId;

                // Create an instance of the test class.
                AsyncDemo ad = new AsyncDemo();

                // Create the delegate.
                AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);

                // Initiate the asychronous call.
                IAsyncResult result = caller.BeginInvoke(3000,
                    out threadId, null, null);

                Thread.Sleep(0);
                Console.WriteLine("Main thread {0} does some work.",
                    Thread.CurrentThread.ManagedThreadId);

                // Wait for the WaitHandle to become signaled.
                result.AsyncWaitHandle.WaitOne();

                // Perform additional processing here.
                // Call EndInvoke to retrieve the results.
                string returnValue = caller.EndInvoke(out threadId, result);

                // Close the wait handle.
                result.AsyncWaitHandle.Close();

                Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".",
                    threadId, returnValue);
            }
        }
    }

    /* This example produces output similar to the following:

    Main thread 1 does some work.
    Test method begins.
    The call executed on thread 3, with return value "My call time was 3000.".
     */
  • 相关阅读:
    数据库面试题
    数据库面试题
    DevExpress GridView 鼠标悬停颜色追踪(行或单元格)
    DevExpress GridView 鼠标悬停颜色追踪(行或单元格)
    2015最新最全最详细的配置win8.1开启IIS和ASP
    2015最新最全最详细的配置win8.1开启IIS和ASP
    打开IIS管理器命令cmd
    打开IIS管理器命令cmd
    C#在方法或属性中使用sealed时的操作与原理
    C#在方法或属性中使用sealed时的操作与原理
  • 原文地址:https://www.cnblogs.com/bayonetxxx/p/2001600.html
Copyright © 2011-2022 走看看