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.".
     */
  • 相关阅读:
    [CF1284E]New Year and Castle Construction
    [BZOJ2178]圆的面积并(格林公式)
    [CF1146H]Satanic Panic(dp)
    [CF1019D]Large Triangle
    [ICPC World Finals 2018][LOJ6409]熊猫保护区(voronoi图)
    [CF gym 101471A][LOJ6470]Airport Construction
    [BZOJ2809]dispatching(左偏树)
    [HDU5784]How Many Triangles
    [CF372E]Drawing circles is fun(反演)
    [NOI2005][BZOJ1502][洛谷P4207]月下柠檬树(自适应Simpson积分)
  • 原文地址:https://www.cnblogs.com/bayonetxxx/p/2001600.html
Copyright © 2011-2022 走看看