Exemplo n.º 1
0
        private IAsyncResult SendMessage(MailMessage message)
        {
            AsyncMethodCaller caller          = new AsyncMethodCaller(SendMailInSeperateThread);
            AsyncCallback     callbackHandler = new AsyncCallback(AsyncCallback);

            return(caller.BeginInvoke(message, callbackHandler, null));
        }
Exemplo n.º 2
0
        public void SendEmail(SendEmailModel model)
        {
            AsyncMethodCaller caller          = new AsyncMethodCaller(SendMailInSeperateThread);
            AsyncCallback     callbackHandler = new AsyncCallback(AsyncCallback);

            caller.BeginInvoke(model, callbackHandler, null);
        }
Exemplo n.º 3
0
        static void Main()
        {
            int threadId;

            AsyncDemo ad = new AsyncDemo();

            AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);

            IAsyncResult result = caller.BeginInvoke(3000,
                                                     out threadId, null, null);

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

            result.AsyncWaitHandle.WaitOne();

            string returnValue = caller.EndInvoke(out threadId, result);

            result.AsyncWaitHandle.Close();

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

            Console.ReadKey(true);
        }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            // Ініціалізація
            byte[][] b = new byte[10000][];

            for (int i = 0; i < b.Length; i++)
            {
                b[i] = new byte[10000];
                for (int j = 0; j < b[i].Length; j++)
                {
                    b[i][j] = 1;
                }
            }

            int[] async_threadId = new int[b.Length];

            for (int i = 0; i < b.Length; i++)
            {
                async_threadId[i] = i;
            }

            List <AsyncMethodCaller> async_caller = new List <AsyncMethodCaller>();
            List <IAsyncResult>      async_res    = new List <IAsyncResult>();

            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();


            // Проходи масив по рядку
            for (int i = 0; i < b.Length; i++)
            {
                AsyncSum          async_sum = new AsyncSum();
                AsyncMethodCaller caller    = new AsyncMethodCaller(async_sum.TestMethod);

                async_caller.Add(caller);

                async_res.Add(async_caller[i].BeginInvoke(b[i], out async_threadId[i], null, null));
            }

            int returnValue;

            for (int i = 0; i < b.Length; i++)
            {
                async_res[i].AsyncWaitHandle.WaitOne();
                returnValue = async_caller[i].EndInvoke(out async_threadId[i], async_res[i]);
                async_res[i].AsyncWaitHandle.Close();

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

            stopWatch.Stop();
            TimeSpan ts = stopWatch.Elapsed;

            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);

            Console.WriteLine("RunTime " + elapsedTime);

            Console.ReadLine();
        }
Exemplo n.º 5
0
            public static void VehiclesAsync()
            {
                AsyncMethodCaller caller   = new AsyncMethodCaller(Vehicles);
                AsyncCallback     callback = new AsyncCallback(AsyncCallback);

                caller.BeginInvoke(callback, null);
            }
Exemplo n.º 6
0
        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);
        }
Exemplo n.º 7
0
        public void SendThat(MailMessage message)
        {
            AsyncMethodCaller caller          = new AsyncMethodCaller(SendMailInSeperateThread);
            AsyncCallback     callbackHandler = new AsyncCallback(AsyncCallback);

            caller.BeginInvoke(message, callbackHandler, null);
        }
Exemplo n.º 8
0
        static void Main(string[] args)
        {
            // The asynchronous method puts the thread id here.
            int threadId;

            // Create the delegate.
            AsyncMethodCaller caller = new AsyncMethodCaller(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();

            // 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);
        }
Exemplo n.º 9
0
        private static void BeginInvokeOnDelegateWithLambdaCallback_DiscardParam()
        {
            var caller = new AsyncMethodCaller(AsyncMethod);

            // here the "_" is actually an identifier, not a discard parameter
            caller.BeginInvoke("delegate", 1, (_) => { }, null); // Noncompliant
        }
        public static void Demo4()
        {
            // Create the delegate.
            AsyncMethodCaller caller = new AsyncMethodCaller(TestMethod);

            // The threadId parameter of TestMethod is an out parameter, so
            // its input value is never used by TestMethod. Therefore, a dummy
            // variable can be passed to the BeginInvoke call. If the threadId
            // parameter were a ref parameter, it would have to be a class-
            // level field so that it could be passed to both BeginInvoke and
            // EndInvoke.
            int dummy = 0;

            // Initiate the asynchronous call, passing three seconds (3000 ms)
            // for the callDuration parameter of TestMethod; a dummy variable
            // for the out parameter (threadId); the callback delegate; and
            // state information that can be retrieved by the callback method.
            // In this case, the state information is a string that can be used
            // to format a console message.
            IAsyncResult result = caller.BeginInvoke(3000,
                                                     out dummy,
                                                     new AsyncCallback(CallbackMethod),
                                                     "The call executed on thread {0}, with return value \"{1}\".");

            Console.WriteLine("The main thread {0} continues to execute...",
                              Thread.CurrentThread.ManagedThreadId);

            // The callback is made on a ThreadPool thread. ThreadPool threads
            // are background threads, which do not keep the application running
            // if the main thread ends. Comment out the next line to demonstrate
            // this.
            Thread.Sleep(4000);

            Console.WriteLine("The main thread ends.");
        }
Exemplo n.º 11
0
        static void Main()
        {
            int threadId;

            AsyncDemo ad = new AsyncDemo();

            AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);

            IAsyncResult result = caller.BeginInvoke(3000,
                out threadId, null, null);

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

            result.AsyncWaitHandle.WaitOne();

            string returnValue = caller.EndInvoke(out threadId, result);

            result.AsyncWaitHandle.Close();

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

            Console.ReadKey(true);
        }
Exemplo n.º 12
0
        static void Start()
        {
            // The asynchronous method puts the thread id here.
            int threadId;

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

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

            // Initiate the asychronous call.
            var 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.
            var 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);

            Console.ReadKey();
        }
        private static void BeginInvokeOnDelegateWithLambdaCallback2()
        {
            var caller   = new AsyncMethodCaller(AsyncMethod);
            var callback = new AsyncCallback(result => { });

            caller.BeginInvoke("delegate", callback, null);  // Noncompliant
        }
Exemplo n.º 14
0
        static void Main(string[] args)
        {
            AsyncMethodCaller caller = new AsyncMethodCaller(DoThis);
            IAsyncResult      result = caller.BeginInvoke(new AsyncCallback(CallBackMethod), null);

            result.AsyncWaitHandle.WaitOne();
        }
Exemplo n.º 15
0
        public DataFrame EndReceive(IAsyncResult ar)
        {
            AsyncResult       result = (AsyncResult)ar;
            AsyncMethodCaller caller = (AsyncMethodCaller)result.AsyncDelegate;

            return(caller.EndInvoke(result));
        }
        private static void BeginInvokeAndEndInvokeOnDelegateWithVariableCallback()
        {
            var           caller   = new AsyncMethodCaller(AsyncMethod);
            AsyncCallback callback = result => { caller.EndInvoke(result); };

            caller.BeginInvoke("delegate", callback, null);  // Compliant
        }
        private static void BeginInvokeAndEndInvokeOnDelegateWithLambdaCallback2()
        {
            var caller   = new AsyncMethodCaller(AsyncMethod);
            var callback = new AsyncCallback(result => caller.EndInvoke(result));

            caller.BeginInvoke("delegate", callback, null);  // Compliant, EndInvoke is called by wrapper.CallEndInvoke
        }
        private static void BeginInvokeAndEndInvokeOnDelegateWithStaticCallback2()
        {
            var caller  = new AsyncMethodCaller(AsyncMethod);
            var wrapper = new CallerWrapper(caller);

            caller.BeginInvoke("delegate", new AsyncCallback(StaticDoNothing), null);  // Noncompliant
        }
        private static void BeginInvokeAndEndInvokeOnDelegateWithStaticCallback1()
        {
            var caller   = new AsyncMethodCaller(AsyncMethod);
            var callback = new AsyncCallback(StaticCallEndInvoke);

            caller.BeginInvoke("delegate", callback, null);  // Compliant, EndInvoke is called by wrapper.CallEndInvoke
        }
Exemplo n.º 20
0
        static void Main(string[] args)
        {
            AsyncMethodCaller caller = new AsyncMethodCaller(TestMethodAsync); // caller 为委托函数
            int threadid             = 0;
            //开启异步操作
            IAsyncResult result = caller.BeginInvoke(1000, out threadid, null, null);

            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("其它业务" + i.ToString());
            }
            //调用EndInvoke,等待异步执行完成
            Console.WriteLine("等待异步方法TestMethodAsync执行完成");
            //等待异步执行完毕信号
            //result.AsyncWaitHandle.WaitOne();
            //Console.WriteLine("收到WaitHandle信号");
            //通过循环不停的检查异步运行状态
            while (result.IsCompleted == false)
            {
                Thread.Sleep(100);
                Console.WriteLine("异步方法,running........");
            }
            //异步结束,拿到运行结果
            string res = caller.EndInvoke(out threadid, result);

            //显示关闭句柄
            result.AsyncWaitHandle.Close();
            Console.WriteLine("关闭了WaitHandle句柄");
            Console.Read();
        }
Exemplo n.º 21
0
        public 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);

            // Call EndInvoke to wait for the asynchronous call to complete,
            // and to retrieve the results.
            string returnValue = caller.EndInvoke(out threadId, result);

            Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".",
                              threadId, returnValue);
        }
        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);

            // Poll while simulating work.
            while (result.IsCompleted == false)
            {
                Thread.Sleep(250);
                Console.Write(".");
            }

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

            Console.WriteLine("\nThe call executed on thread {0}, with return value \"{1}\".", threadId, returnValue);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Executes a particular function in a module, according to the passed in parameters, acting as a slave server
        /// </summary>
        /// <param id="state">The server state object of the request</param>
        public static void ExecutionBegin(ServerState state)
        {
            //finally execute the function defined in the transfer
            AsyncMethodCaller execution = new AsyncMethodCaller(execute);

            execution.BeginInvoke(state, null, null);
        }
Exemplo n.º 24
0
            public object DoWork(MB.Util.AsynWorkThread workThread, DoWorkEventArgs e)
            {
                // 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);
                workThread.ReportProgress(0, string.Format("Main thread {0} does some work.",
                                                           Thread.CurrentThread.ManagedThreadId));

                // Call EndInvoke to wait for the asynchronous call to complete,
                // and to retrieve the results.
                string returnValue = caller.EndInvoke(out threadId, result);

                workThread.ReportProgress(1, string.Format("The call executed on thread {0}, with return value \"{1}\".",
                                                           threadId, returnValue));

                e.Result = returnValue;
                return(returnValue);
            }
Exemplo n.º 25
0
        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);

            // Poll while simulating work.
            while (result.IsCompleted == false)
            {
                Thread.Sleep(250);
                Console.Write(".");
            }

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

            Console.WriteLine("\nThe call executed on thread {0}, with return value \"{1}\".",
                              threadId, returnValue);
        }
Exemplo n.º 26
0
 private void button3_Click(object sender, EventArgs e)
 {
     var caller = new AsyncMethodCaller(AsyncMethod);
     MessageBox.Show("Task Created.");
     IAsyncResult result = caller.BeginInvoke(2000, CallbackMethod, null);
     MessageBox.Show("Task BeginInvoke.");
 }
Exemplo n.º 27
0
        protected void Page_Load(object sender, EventArgs e)
        {
            #region
            // The asynchronous method puts the thread id here.
            int threadId;
            // Create the delegate.
            AsyncMethodCaller caller = new AsyncMethodCaller(TestMethod);

            // Initiate the asychronous call.
            IAsyncResult result = caller.BeginInvoke(3000,
                                                     out threadId, null, null);
            string returnValue = caller.EndInvoke(out threadId, result);
            #endregion

            #region
            //Async async = null;
            //async = new Async(o =>
            //        {

            //            return "异步返回值";
            //        });
            //r = async.BeginInvoke("异步测试", new AsyncCallback(Done), async);
            //r.AsyncWaitHandle.WaitOne();

            #endregion
        }
Exemplo n.º 28
0
        //EndInvokeによるブロッキング
        static void BlockingEndInvoke()
        {
            // 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);

            // Call EndInvoke to wait for the asynchronous call to complete,
            // and to retrieve the results.
            string returnValue = caller.EndInvoke(out threadId, result);

            Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".",
                threadId, returnValue);
        }
Exemplo n.º 29
0
        // On "Connect" button clicked
        private void ConnectButton_Click(object sender, EventArgs e)
        {
            if (videoDevice != null)
            {
                if ((videoCapabilities != null) && (videoCapabilities.Length != 0))
                {
                    videoDevice.VideoResolution = videoCapabilities[videoResolutionsCombo.SelectedIndex];
                }

                if ((snapshotCapabilities != null) && (snapshotCapabilities.Length != 0))
                {
                    videoDevice.ProvideSnapshots   = true;
                    videoDevice.SnapshotResolution = snapshotCapabilities[snapshotResolutionsCombo.SelectedIndex];
                    videoDevice.SnapshotFrame     += new NewFrameEventHandler(VideoDevice_SnapshotFrame);
                }

                EnableConnectionControls(false);

                videoSourcePlayer.VideoSource = videoDevice;

                videoDevice.NewFrame += new NewFrameEventHandler(Video_NewFrame);
                caller = SaveVideo;

                videoSourcePlayer.Start( );
            }
        }
Exemplo n.º 30
0
        string Execute_Update()
        {
            for (int i = 1; i <= numberofexchanges; i++)
            {
                //mk.UpdateExchange(i);
                int threadId;
                AsyncMethodCaller caller = new AsyncMethodCaller(CallMarkets);

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

                hsnumberofthreads.Add(i, result);
            }

            /*
             * while (hsnumberofthreads.Count > 0)
             * {
             *
             * }*/

            WaitHandle[] waitHandles = new WaitHandle[numberofexchanges];
            foreach (DictionaryEntry entry in hsnumberofthreads)
            {
                IAsyncResult tempresult = (IAsyncResult)entry.Value;
                waitHandles[Convert.ToInt32(entry.Key) - 1] = tempresult.AsyncWaitHandle;
            }
            WaitHandle.WaitAll(waitHandles);

            hsnumberofthreads.Clear();

            return("");
        }
Exemplo n.º 31
0
        static void PrintResult(IAsyncResult result)
        {
            AsyncResult       asyncResult = (AsyncResult)result;
            AsyncMethodCaller caller      = (AsyncMethodCaller)asyncResult.AsyncDelegate;
            // Retreaving previously stored number.
            decimal number = (decimal)result.AsyncState;

            try
            {
                // Call EndInvoke to retrieve the results.
                bool isPrime = caller.EndInvoke(out double seconds, result);
                if (isPrime)
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine($"Number {number} is prime. Elapsed time {seconds} s.");
                    Console.ForegroundColor = ConsoleColor.Gray;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine($"Number {number} is composite. Elapsed time {seconds} s.");
                    Console.ForegroundColor = ConsoleColor.Gray;
                }
            }
            catch (Exception ex) // Exceptions from async operations will appear here.
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex.Message);
                Console.ForegroundColor = ConsoleColor.Gray;
                return;
            }
        }
Exemplo n.º 32
0
        /// <summary>
        /// Envoyer Email (d'une manière asynchrone) avec un template dans le dossier du template (appsettings EmailTemplatesFolder dans le web.config)
        /// </summary>
        /// <param name="model">Le model de l'email</param>
        /// <param name="template">Le nom complet du template. Ne pas oublier de déployer le dossier du template avec l'application</param>
        public void SendEmail(EmailModelBase model, string template)
        {
            AsyncMethodCaller caller          = new AsyncMethodCaller(SendMailInSeperateThread);
            AsyncCallback     callbackHandler = new AsyncCallback(AsyncCallback);

            caller.BeginInvoke(model, template, callbackHandler, null);
        }
Exemplo n.º 33
0
            public static void ContactsAsync()
            {
                AsyncMethodCaller caller   = new AsyncMethodCaller(Contacts);
                AsyncCallback     callback = new AsyncCallback(AsyncCallback);

                caller.BeginInvoke(callback, null);
            }
Exemplo n.º 34
0
        private void GetResult(IAsyncResult result)
        {
            AsyncMethodCaller caller       = (AsyncMethodCaller)((AsyncResult)result).AsyncDelegate;
            string            returnstring = caller.EndInvoke(result);

            sc.Post(ShowState, returnstring);
        }
Exemplo n.º 35
0
    protected void Page_Load(object sender, EventArgs e)
    {
        Debug.WriteLine("Starting");

        DateTime? a = new DateTime(2000, 12, 5);
        a = null;

        TheDelegate delegateDefinition = s => s;
        string theReturnValue = delegateDefinition("test");

        AsyncDemo ad = new AsyncDemo();

        AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);
        int dummy = 0;
        IAsyncResult result = caller.BeginInvoke(3000,
            out dummy,
            new AsyncCallback(CallbackMethod),
            "The call executed on thread {0}, with return value \"{1}\".");

        Debug.WriteLine(string.Format("The main thread {0} continues to execute...",
            Thread.CurrentThread.ManagedThreadId));

        //Thread.Sleep(4000);

        Debug.WriteLine("The main thread ends.");
    }
Exemplo n.º 36
0
        private void CpuAPMExcution()
        {
            var sw = Stopwatch.StartNew(); // time the operation
            // The asynchronous method puts the thread id here.
            int threadId;

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

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

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

            Thread.Sleep(0);

            var test = DoWork(_digits.Value);

            _pi.AppendText(test);

            // 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();

            textBoxPerformance.Text = Convert.ToString(sw.Elapsed);
            _pi.AppendText($" (The call executed on thread {threadId}). ");
        }
Exemplo n.º 37
0
 public void Send(MailMessage message)
 {
     MailMessage msg = new MailMessage();
     msg = message;
     AsyncMethodCaller caller = new AsyncMethodCaller(SendMailInSeperateThread);
     AsyncCallback callbackHandler = new AsyncCallback(AsyncCallback);
     caller.BeginInvoke(msg, callbackHandler, null);
 }
        private static void BeginInvokeAndEndInvokeOnDelegateWithoutCallback()
        {
            Console.WriteLine("BeginInvokeAndEndInvokeOnDelegateWithoutCallback");
            var          caller = new AsyncMethodCaller(AsyncMethod);
            IAsyncResult result = caller.BeginInvoke("delegate", /* callback */ null, /* state */ null); // Compliant

            caller.EndInvoke(result);
        }
Exemplo n.º 39
0
        static void Main(string[] args)
        {
            // Ініціалізація
            byte[][] b = new byte[10000][];

            for (int i = 0; i < b.Length; i++)
            {
                b[i] = new byte[10000];
                for (int j = 0; j < b[i].Length; j++)
                {
                    b[i][j] = 1;
                }
            }

            int[] async_threadId = new int[b.Length];

            for (int i = 0; i < b.Length; i++)
            {
                async_threadId[i] = i;
            }

            List<AsyncMethodCaller> async_caller = new List<AsyncMethodCaller>();
            List<IAsyncResult> async_res = new List<IAsyncResult>();

            Stopwatch stopWatch = new Stopwatch();
            stopWatch.Start();

            // Проходи масив по рядку
            for (int i = 0; i < b.Length; i++)
            {
                AsyncSum async_sum = new AsyncSum();
                AsyncMethodCaller caller = new AsyncMethodCaller(async_sum.TestMethod);

                async_caller.Add(caller);

                async_res.Add (async_caller[i].BeginInvoke( b[i], out async_threadId[i], null, null) );

            }

            int returnValue;

            for (int i = 0; i < b.Length; i++)
            {
                async_res[i].AsyncWaitHandle.WaitOne();
                returnValue = async_caller[i].EndInvoke(out async_threadId[i], async_res[i]);
                async_res[i].AsyncWaitHandle.Close();

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

            stopWatch.Stop();
            TimeSpan ts = stopWatch.Elapsed;

            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
            Console.WriteLine("RunTime " + elapsedTime);

            Console.ReadLine();
        }
Exemplo n.º 40
0
        private void button2_Click(object sender, EventArgs e)
        {
            var caller = new AsyncMethodCaller(AsyncMethod);
            MessageBox.Show("Task Created.");
            IAsyncResult result = caller.BeginInvoke(2000, null ,null);
            MessageBox.Show("Task BeginInvoke.");
            Thread.Sleep(100);

            caller.EndInvoke(result);
            MessageBox.Show("Task EndInvoke.");
        }
Exemplo n.º 41
0
        public void BuyNumber(Int32 number, Action<NumberType> callback)
        {
            // no lock is needed here since just checking if a number is prime
            // and its a readonly operation.
            if (!_primes.ContainsKey(number))
            {
                callback(NumberType.NotExist);
            }
            else
            {
                // Create the delegate.
                AsyncMethodCaller caller = new AsyncMethodCaller(BuyPrime);

                // Initiate the asychronous call.
                caller.BeginInvoke(number, callback, null, null);
            }
        }
Exemplo n.º 42
0
        public static void Main(string[] args)
        {
            // Create an instance of the test class.
            AsyncDemo ad = new AsyncDemo();

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

            // The threadId parameter of TestMethod is an out parameter, so
            // its input value is never used by TestMethod. Therefore, a dummy
            // variable can be passed to the BeginInvoke call. If the threadId
            // parameter were a ref parameter, it would have to be a class-
            // level field so that it could be passed to both BeginInvoke and
            // EndInvoke.
            int dummy = 0;

            // Initiate the asynchronous call, passing three seconds (3000 ms)
            // for the callDuration parameter of TestMethod; a dummy variable
            // for the out parameter (threadId); the callback delegate; and
            // state information that can be retrieved by the callback method.
            // In this case, the state information is a string that can be used
            // to format a console message.
            IAsyncResult result = caller.BeginInvoke(3000,
                out dummy,
                new AsyncCallback(CallbackMethod),
                "The call executed on thread {0}, with return value \"{1}\".");

            Console.WriteLine("The main thread {0} continues to execute...",
                Thread.CurrentThread.ManagedThreadId);

            // The callback is made on a ThreadPool thread. ThreadPool threads
            // are background threads, which do not keep the application running
            // if the main thread ends. Comment out the next line to demonstrate
            // this.
            Thread.Sleep(4000);

            Console.WriteLine("The main thread ends.");

            Console.ReadKey();
        }
Exemplo n.º 43
0
        public ActionResult Index()
        {
            var client = new FlickrService.FlickrService();

            AsyncMethodCaller caller = new AsyncMethodCaller(client.GetRecentPhotos);

            var result = caller.BeginInvoke(null, null);

            var photos = caller.EndInvoke(result);

            ViewData["flickrphotos"] = photos;

            List<string> urls = new List<string>();
            foreach (var photo in photos)
            {
                urls.Add(photo.ImageUrl);
            }

            ViewData["photos"] = urls;

            return View();
        }
Exemplo n.º 44
0
        static void Main()
        {
            AsyncDemo ad = new AsyncDemo();

            AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);

            int dummy = 0;

            IAsyncResult result = caller.BeginInvoke(3000,
                out dummy,
                new AsyncCallback(CallbackMethod),
                "The call executed on thread {0}, with return value \"{1}\".");

            Console.WriteLine("The main thread {0} continues to execute...",
                Thread.CurrentThread.ManagedThreadId);

            Thread.Sleep(4000);

            Console.WriteLine("The main thread ends.");

            Console.ReadKey(true);
        }
Exemplo n.º 45
0
        static int Main(string[] args)
        {
            IAsyncResult result = null;
            AsyncMethodCaller caller = new AsyncMethodCaller(DelegateCommon.TestMethod);

            try
            {
                result = caller.BeginInvoke(123, null, null);
            }
            catch (PlatformNotSupportedException)
            {
                // Expected
            }
            catch (Exception ex)
            {
                Console.WriteLine("BeginInvoke resulted in unexpected exception: {0}", ex.ToString());
                Console.WriteLine("FAILED!");
                return -1;
            }

            try
            {
                caller.EndInvoke(result);
            }
            catch (PlatformNotSupportedException)
            {
                // Expected
            }
            catch (Exception ex)
            {
                Console.WriteLine("EndInvoke resulted in unexpected exception: {0}", ex.ToString());
                Console.WriteLine("FAILED!");
                return -1;
            }

            return 100;
        }
Exemplo n.º 46
0
        static void Main()
        {
            int threadId;

            AsyncDemo ad = new AsyncDemo();

            AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);

            IAsyncResult result = caller.BeginInvoke(3000,
                out threadId, null, null);

            while (result.IsCompleted == false)
            {
                Thread.Sleep(250);
                Console.Write(".");
            }

            string returnValue = caller.EndInvoke(out threadId, result);

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

            Console.ReadKey(true);
        }
Exemplo n.º 47
0
 public void FoundWayAsync(Point startPosition, Point endPosition)
 {
     HasEnded = false;
     AsyncMethodCaller caller = new AsyncMethodCaller(FoundPath);
     caller.BeginInvoke(startPosition, endPosition, null, null);
     // Thread thread = new Thread(caller(startPosition, endPosition, out path, creature, improvedPathFinding, ignoreObstacles)});
 }
        private void btnBatchUpdateLocalAssembly_Click(object sender, EventArgs e)
        {
            tabMain.SelectedTab = tabPageMessage;

            if (Configuration.MasterConfig.BatchUpdateAssemblySettings.AutoUpdate)
            {
                AsyncMethodCaller caller = new AsyncMethodCaller(InitializeDropdowns);
                IAsyncResult result = caller.BeginInvoke(
                    null,
                    caller);

                caller.EndInvoke(result);

                for (int i = 0; i < cmbVersion.Items.Count; i++)
                {
                    cmbVersion.SelectedIndex = i;
                    for (int j = 1; j < cmbModule.Items.Count; j++)
                    {
                        cmbModule.SelectedIndex = j;

                        foreach (String uri in Configuration.MasterConfig.BatchUpdateAssemblySettings.UpdateModuleNames)
                        {
                            if (uri.ToLower() == cmbModule.Text.ToLower())
                            {
                                string updateUrl = textEndPointUri.Text.ToLower();
                                if (!updateUrls.Contains(updateUrl))
                                {
                                    updateUrls.Add(updateUrl);
                                }
                            }
                        }
                    }
                }
            }

            string[] updateVersions = Configuration.MasterConfig.BatchUpdateAssemblySettings.UpdateVersions;
            string[] updateModuleNames = Configuration.MasterConfig.BatchUpdateAssemblySettings.UpdateModuleNames;

            if (updateVersions != null && updateModuleNames != null)
            {
                for (int i = 0; i < updateVersions.Length; i++)
                {
                    for (int j = 0; j < updateModuleNames.Length; j++)
                    {
                        string updateUrl = updateVersions[i] + updateModuleNames[j];
                        if (!updateUrls.Contains(updateUrl))
                        {
                            updateUrls.Add(updateUrl);
                        }
                    }
                }
            }

            beginUpdateLocalAssembly = 0;
            finishedUpdateLocalAssembly = 0;
            btnBatchUpdateLocalAssembly.Enabled = false;

            foreach (string updateUrl in updateUrls)
            {
                beginUpdateLocalAssembly++;
                Wsdl wsdl1 = new Wsdl();
                wsdl1.Paths.Add(updateUrl);

                AsyncMethodCaller caller1 = new AsyncMethodCaller(wsdl1.GenerateAndUpdateAssembly);
                caller1.BeginInvoke(
                    new AsyncCallback(BatchUpdateLocalAssemblyCallBack),
                    caller1);
                ShowMessage(this, MessageType.Begin,
                            "Begin Create Local Assembly Use EndPointUri: " + updateUrl);
            }
        }
Exemplo n.º 49
0
        /// <summary>
        /// Main: Async operation beginning using WaitOne (waithandler)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <param name="cb"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        IAsyncResult BeginAsyncOperation(object sender,EventArgs e,AsyncCallback cb,object state)
        {
            // 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);

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

            // Initiate the asychronous call.
            IAsyncResult result = caller.BeginInvoke(3000,
                                                     out threadId, 
                                                     //null, null);
                new AsyncCallback(EndAsyncOperation),
                "The call executed on thread {0}, with return value \"{1}\".");

            Trace.Write("BeginAsyncOperation",
               string.Format("Waiting for the WaitHandle to become signaled...\nThreadId={0} \tResultState = {1}\t Caller= {2}) ", 
               threadId, result.AsyncState, caller));

            result.AsyncWaitHandle.WaitOne();

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

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

            Queue<int> threadIds = m_TaskIds;// Session["TaskIds"] as Queue<int>;
            if (threadIds != null) threadIds.Enqueue(threadId);
            IDictionary<int, IAsyncResult> asyncResult = m_AsyncResults;// Session["AsyncResults"] as Dictionary<int, IAsyncResult>;
            if (asyncResult != null) asyncResult.Add(new KeyValuePair<int, IAsyncResult>(threadId, result));
            IDictionary<int, AsyncMethodCaller> asyncCallers = m_AsyncCallers;// Session["AsyncCallers"] as Dictionary<int, AsyncMethodCaller>;
            if (asyncCallers != null) asyncCallers.Add(new KeyValuePair<int, AsyncMethodCaller>(threadId, caller));

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

            return result;

        }
 /// <summary>
 /// The dependencies are injected.
 /// </summary>
 /// <param name="asyncMethodCaller">Use TestAsyncMethodCaller for tests, AsyncMethodCaller in production.</param>
 /// <param name="service">Inject the service for easier faking and faster tests.</param>
 public ViewModel(AsyncMethodCaller asyncMethodCaller, IServiceInterface service)
 {
     this.asyncMethodCaller = asyncMethodCaller;
     this.service = service;
 }
Exemplo n.º 51
0
Arquivo: AStar.cs Projeto: mokujin/DN
 public void FoundWayAsync(Point startPosition, Point endPosition)
 {
     HasEnded = false;
     AsyncMethodCaller caller = new AsyncMethodCaller(FindPath);
     caller.BeginInvoke(startPosition, endPosition, null, null);
 }
Exemplo n.º 52
0
        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);
            IAsyncResult result;

            #region Using Begin and End Invoke
            Console.WriteLine("Beginning solely end invoke method...");
            // Initiate the asynchronous call.
            result = caller.BeginInvoke(1111, out threadId, null, null);

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

            // Call EndInvoke to wait for the asynchronous call to complete,
            // and to retrieve the results.
            string returnValue = caller.EndInvoke(out threadId, result);

            Console.WriteLine("The call executed on thread {0}, has completed using EndInvoke (blocking) with return value \"{1}\".", threadId, returnValue);
            Console.WriteLine();
            #endregion

            ad = new AsyncDemo();
            caller = new AsyncMethodCaller(ad.TestMethod);

            #region Using a Wait Handle
            Console.WriteLine("Beginning wait handle method...");
            result = caller.BeginInvoke(1234, out threadId, null, null);

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

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

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

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

            Console.WriteLine("The called executed on thread {0}, has completed using a Wait Handle with return value \"{1}\".", threadId, returnValue);
            Console.WriteLine();
            #endregion

            ad = new AsyncDemo();
            caller = new AsyncMethodCaller(ad.TestMethod);

            #region Using Polling
            Console.WriteLine("Beginning polling method...");
            result = caller.BeginInvoke(1010, out threadId, null, null);

            // Poll while simulating work.
            while (result.IsCompleted == false)
            {
                Thread.Sleep(250);
                Console.Write(".");
            }

            returnValue = caller.EndInvoke(out threadId, result);

            Console.WriteLine("\nThe call executed on thread {0}, has completed using polling with return value \"{1}\".", threadId, returnValue);
            Console.WriteLine();
            #endregion

            ad = new AsyncDemo();
            caller = new AsyncMethodCaller(ad.TestMethod);

            #region Using an AsyncCallBack method
            Console.WriteLine("Beginning asynchronous callback method...");
            /*
            AsyncCallback callback = new AsyncCallback(ad.AsyncCallBackMethod);
            result = caller.BeginInvoke(1234, out threadId, callback, null);

            callback(result);
            */
            result = caller.BeginInvoke(1234, out threadId, new AsyncCallback(ad.AsyncCallBackMethod),
                "The call executed on thread {0}, with return value \"{1}\".");

            Console.WriteLine("The main thread {0} continues to execute...", Thread.CurrentThread.ManagedThreadId);

            // The callback is made on a threadpool thread. Threadpool threads
            // are background threads, which do not keep the application running
            // if the main thread ends. Comment out the next line to demonstrate
            // this.
            Thread.Sleep(4000);

            Console.WriteLine("The main thread ends.");
            Console.WriteLine();
            #endregion

            #region My own test
            Console.WriteLine("Running my own test...");
            AsyncThingy thingy = new AsyncThingy();
            thingy.DoAsyncStuff();
            Console.WriteLine("Main thread {0} is back.", Thread.CurrentThread.ManagedThreadId);
            Console.WriteLine("The asynchronous method should write something shortly, or stuff will explode");
            Thread.Sleep(6000);
            #endregion
        }
Exemplo n.º 53
0
 public AsyncThingy()
 {
     myAd = new AsyncDemo();
     caller = new AsyncMethodCaller(myAd.TestMethod);
 }
Exemplo n.º 54
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (txtParameters.Count > 0)
            {
                if (MessageBox.Show("请确认参数是否全部填写正确!", "系统提示",
                    MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
                    return;
            }

            button1.Enabled = false;

            label5.Text = "正在调用服务,请稍候...";
            label5.Refresh();

            var jValue = new JObject();
            if (txtParameters.Count > 0)
            {
                foreach (var p in txtParameters)
                {
                    var text = p.Value.Text.Trim();
                    if (!string.IsNullOrEmpty(text))
                    {
                        var info = p.Value.Tag as ParameterInfo;

                        try
                        {
                            jValue[p.Key] = JToken.Parse(text);
                        }
                        catch
                        {
                            jValue[p.Key] = text;
                        }
                    }
                }
            }

            //提交的参数信息
            string parameter = jValue.ToString(Newtonsoft.Json.Formatting.None);
            var message = new InvokeMessage
            {
                ServiceName = serviceName,
                MethodName = methodName,
                Parameters = parameter
            };

            //启用线程进行数据填充
            var caller = new AsyncMethodCaller(AsyncCaller);
            var ar = caller.BeginInvoke(message, AsyncComplete, caller);
        }
        private void AsyncInitializeDropdowns()
        {
            btnPopulate.Enabled = false;
            cmbModule.Enabled = false;
            cmbVersion.Enabled = false;
            ServerCBox.Enabled = false;
            buttonGet.Enabled = false;

            AsyncMethodCaller caller = new AsyncMethodCaller(InitializeDropdowns);
            caller.BeginInvoke(
                new AsyncCallback(InitializeDropdownsCallBack),
                caller);
        }
Exemplo n.º 56
0
 /// <summary>
 /// Load a category of videos into this carousel.
 /// Everything calling the webservice and downloading of coverart is run in a background thread.
 /// </summary>
 /// <param name="category"></param>
 public void Add(string category)
 {
     AsyncMethodCaller caller = new AsyncMethodCaller(InternalAdd);
     IAsyncResult result = caller.BeginInvoke(category, null, null);
 }
Exemplo n.º 57
0
 private void RegenerateCache(string url)
 {
     var method = new AsyncMethodCaller(GenerateIndexesFor);
     method.BeginInvoke(url, null, null);
 }
Exemplo n.º 58
0
 void AsyncJobByDelegate()
 {
     AsyncMethodCaller caller = new AsyncMethodCaller(SleepJob);
     caller.BeginInvoke(GetResult, null);
 }
Exemplo n.º 59
0
        private void startSync()
        {
            AsyncMethodCaller caller = new AsyncMethodCaller(logic.syncFolderPair);

            while (lvTaskList.Items.Count > 0)
            {
                string taskName = lvTaskList.Items[0].SubItems[0].Text;

                lblTimer.Text = "Synchronizing folder pair in " + taskName;
                statusBar.Refresh();

                string source = lvTaskList.Items[0].SubItems[1].Text;
                string target = lvTaskList.Items[0].SubItems[2].Text;

                //IAsyncResult result = caller.BeginInvoke(source, target, taskName, null, null);
                logic.syncFolderPair(source, target, taskName);

                plugSyncList.Remove(new SyncTask(taskName, source, target));
                updateListView();
            }
        }
Exemplo n.º 60
0
        private void DoTestAsyncOperation()
        {
            // The asynchronous method puts the thread id here.
            int threadId;

            // Create an instance of the test class.
            AsyncDemo ad = new AsyncDemo(HttpContext.Current.Session, HttpContext.Current.Trace);

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

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

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

            result.AsyncWaitHandle.WaitOne();
            Trace.Write("BeginAsyncOperation",
               string.Format("Waiting for the WaitHandle to become signaled...\nThreadId={0} \tResultState = {1}\t Caller= {2}",
               threadId, result.AsyncState, caller));

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

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

            Queue<int> threadIds = m_TaskIds;// Session["TaskIds"] as Queue<int>;
            if (threadIds != null) threadIds.Enqueue(threadId);
            if (m_AsyncResults != null) m_AsyncResults.Add(threadId, result);

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