예제 #1
0
        private void GetResult(IAsyncResult result)
        {
            AsyncMethodCaller caller       = (AsyncMethodCaller)((AsyncResult)result).AsyncDelegate;
            string            returnstring = caller.EndInvoke(result);

            sc.Post(ShowState, returnstring);
        }
예제 #2
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);
        }
예제 #3
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();
        }
예제 #4
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);
        }
예제 #5
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);
        }
예제 #6
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);
        }
예제 #7
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);
        }
        private static void BeginInvokeAndEndInvokeOnDelegateWithVariableCallback()
        {
            var           caller   = new AsyncMethodCaller(AsyncMethod);
            AsyncCallback callback = result => { caller.EndInvoke(result); };

            caller.BeginInvoke("delegate", callback, null);  // Compliant
        }
예제 #9
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);
        }
예제 #10
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);
            }
예제 #11
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}). ");
        }
예제 #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();
        }
예제 #13
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);
        }
        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
        }
예제 #15
0
        public DataFrame EndReceive(IAsyncResult ar)
        {
            AsyncResult       result = (AsyncResult)ar;
            AsyncMethodCaller caller = (AsyncMethodCaller)result.AsyncDelegate;

            return(caller.EndInvoke(result));
        }
예제 #16
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
        }
        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);
        }
예제 #18
0
        public static void CallBackMethod(IAsyncResult ar)
        {
            AsyncResult       result      = (AsyncResult)ar;
            AsyncMethodCaller caller      = (AsyncMethodCaller)result.AsyncDelegate;
            string            returnValue = caller.EndInvoke(result);

            Console.WriteLine(returnValue);
        }
        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);
        }
예제 #20
0
        private void UpdateListViewCallback(IAsyncResult result)
        {
            AsyncResult       ar     = (AsyncResult)result;
            AsyncMethodCaller caller = (AsyncMethodCaller)ar.AsyncDelegate;
            var records = caller.EndInvoke(result);

            listView1.BeginInvoke(new InvokeDelegate(UpdateListView), new object[] { records });
        }
예제 #21
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);

            // #3 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 threadId,
            //    new AsyncCallback(CallbackMethod),
            //    "The call executed on thread {0}, with return value \"{1}\".");


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

            // After calling BeginInvoke you can do the following:
            // Do some work and then call EndInvoke to block until the call completes.
            // Obtain a WaitHandle using the IAsyncResult.AsyncWaitHandle property, use its WaitOne method to block execution until the WaitHandle is signaled, and then call EndInvoke.
            // Poll the IAsyncResult returned by BeginInvoke to determine when the asynchronous call has completed, and then call EndInvoke.
            // Pass a delegate for a callback method to BeginInvoke. The method is executed on a ThreadPool thread when the asynchronous call completes. The callback method calls EndInvoke.

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

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

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

            // Perform additional processing here.

            // Call EndInvoke to retrieve the results. Will wait if you didn't do that previously.
            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);
        }
예제 #22
0
    public void DeleteRole()
    {
        ShowDialog("删除角色", "确定要删除角色吗?", true);
        string data = Processor.C2SDeleteRole(player.userId, player.roles [player.selectedRole].id);

        if (!player.IsLogined())
        {
            Debug.LogError("player do not login!");
            ShowDialog("删除角色", "与服务器断开或用户未登陆!", true, () => {
                player.Logout();
                SceneManager.LoadScene("start");
            }, () => {
                player.Logout();
                SceneManager.LoadScene("start");
            });
        }
        ShowDialog("删除角色", "处理中...", false);
        player.Send(data);
        AsyncMethodCaller caller = new AsyncMethodCaller(DeleteRoleRespone);
        IAsyncResult      result = caller.BeginInvoke(null, null);
        bool success             = result.AsyncWaitHandle.WaitOne(10000, true);

        if (!success)
        {
            Debug.Log("Time Out");
            ShowDialog("删除角色", "操作超时", true, () => {
                HideDialog();
            }, () => {
                HideDialog();
            });
        }
        else
        {
            int returnValue = caller.EndInvoke(result);
            if (returnValue != 0)
            {
                success = false;
                ShowDialog("删除角色", "操作失败", true, () => {
                    HideDialog();
                }, () => {
                    HideDialog();
                });
            }
        }
        result.AsyncWaitHandle.Close();
        if (success)
        {
            Debug.Log("Success!");
            ShowDialog("删除角色", "操作成功!", true, () => {
                HideDialog();
                UpdateItems();
            }, () => {
                HideDialog();
                UpdateItems();
            });
        }
    }
예제 #23
0
        // 异步操作完成时执行的方法
        private void GetResult(IAsyncResult result)
        {
            AsyncMethodCaller caller = (AsyncMethodCaller)((AsyncResult)result).AsyncDelegate;
            // 调用EndInvoke去等待异步调用完成并且获得返回值
            // 如果异步调用尚未完成,则 EndInvoke 会一直阻止调用线程,直到异步调用完成
            string returnstring = caller.EndInvoke(result);

            //sc.Post(ShowState,resultvalue);
            rtbState.Text = returnstring;
        }
예제 #24
0
        static void Main(string[] args)
        {
            AsyncMethodCaller caller = new AsyncMethodCaller(test);

            var result = caller.BeginInvoke(2, new AsyncCallback(fun), null);

            caller.EndInvoke(result);

            Console.ReadKey();
        }
예제 #25
0
        // 回调方法
        private void GetResult(IAsyncResult result)
        {
            AsyncMethodCaller caller = (AsyncMethodCaller)((AsyncResult)result).AsyncDelegate;
            // 调用EndInvoke去等待异步调用完成并且获得返回值
            // 如果异步调用尚未完成,则 EndInvoke 会一直阻止调用线程,直到异步调用完成
            string resultvalue = caller.EndInvoke(result);

            //sc.Post(ShowState,resultvalue);
            richTextBox1.Invoke(_showStateCallback, resultvalue);
        }
예제 #26
0
        //异步操作完成回调
        private void GetResultCB(IAsyncResult result)
        {
            //获取异步调用的委托对象
            AsyncMethodCaller amc1      = (AsyncMethodCaller)((AsyncResult)result).AsyncDelegate;
            string            resultStr = amc1.EndInvoke(result);

            // 通过获得GUI线程的同步上下文的派生对象,
            // 然后调用Post方法来使更新GUI操作方法由GUI 线程去执行
            sc.Post(ShowState, resultStr);
        }
예제 #27
0
        // 异步操作完成时执行的方法
        private void GetResult(IAsyncResult result)
        {
            AsyncMethodCaller caller = (AsyncMethodCaller)((AsyncResult)result).AsyncDelegate;
            // 调用EndInvoke去等待异步调用完成并且获得返回值
            // 如果异步调用尚未完成,则 EndInvoke 会一直阻止调用线程,直到异步调用完成
            string returnstring = caller.EndInvoke(result);

            // 通过获得GUI线程的同步上下文的派生对象,
            // 然后调用Post方法来使更新GUI操作方法由GUI 线程去执行
            sc.Post(ShowState, returnstring);
        }
예제 #28
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.");
        }
예제 #29
0
        private void GetResult(IAsyncResult result)
        {
            int threadId;
            AsyncMethodCaller caller = (AsyncMethodCaller)((AsyncResult)result).AsyncDelegate;
            // 调用EndInvoke去等待异步调用完成并且获得返回值
            // 如果异步调用尚未完成,则 EndInvoke 会一直阻止调用线程,直到异步调用完成
            string resultvalue = caller.EndInvoke(out threadId, result);

            Console.WriteLine($"{resultvalue}{Environment.NewLine}结果方法运行的线程:{Environment.CurrentManagedThreadId}");
            btnAsync.Enabled = true;
        }
예제 #30
0
        //call backs also run in the same thread in which begin invoke runs on.
        static void callBack(IAsyncResult iAsynResult)
        {
            string            infoPassed = (string)iAsynResult.AsyncState;
            AsyncResult       AsResult   = (AsyncResult)iAsynResult;
            AsyncMethodCaller op         = (AsyncMethodCaller)AsResult.AsyncDelegate;
            int res = op.EndInvoke(iAsynResult);

            Console.WriteLine("Infor passed from BegingInvoke: " + infoPassed);

            Console.WriteLine("[{0}] Call back method res ={1}", Thread.CurrentThread.ManagedThreadId, res);
        }
예제 #31
0
        // Callback method must have the same signature as the
        // AsyncCallback delegate.
        static void CallbackMethod(IAsyncResult ar)
        {
            // Retrieve the delegate.
            AsyncMethodCaller caller = (AsyncMethodCaller)ar.AsyncState;

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

            Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".",
                              threadId, returnValue);
        }
예제 #32
0
    private void TryLogin()
    {
        if (m_userid == null || m_password == null)
        {
            return;
        }
        string userid   = m_userid.text;
        string password = m_password.text;

        if (userid.Length == 0 || password.Length == 0)
        {
            ShowDialog("登陆", "用户名或密码不能为空", true);
            return;
        }
        string data = Processor.C2SLogin(userid, password);

        if (!player.IsConnected())
        {
            if (!player.Connect("127.0.0.1", 8888))
            {
                Debug.LogError("Connected failed!");
                ShowDialog("登陆", "无法连接到服务器!", true);
                return;
            }
        }
        ShowDialog("登陆", "处理中...", false);
        player.Send(data);
        AsyncMethodCaller caller = new AsyncMethodCaller(Respone);
        IAsyncResult      result = caller.BeginInvoke(null, null);
        bool success             = result.AsyncWaitHandle.WaitOne(10000, true);

        if (!success)
        {
            Debug.Log("Time Out");
            ShowDialog("登陆", "登陆超时", true);
        }
        else
        {
            int returnValue = caller.EndInvoke(result);
            if (returnValue != 0)
            {
                success = false;
                ShowDialog("登陆", "登陆失败", true);
            }
        }
        result.AsyncWaitHandle.Close();
        m_password.text = "";
        if (success)
        {
            player.Login(userid);
            SceneManager.LoadScene("select");
        }
    }
예제 #33
0
        public static void RunSample(string name, int time)
        {
            int threadId;
            DelegateSample_AsyncFlowcast daf = new DelegateSample_AsyncFlowcast(name, time);
            AsyncMethodCaller            amc = new AsyncMethodCaller(daf.Working);
            IAsyncResult result = amc.BeginInvoke(out threadId, null, null);

            Console.WriteLine("Main thread {0} dose some work.", Thread.CurrentThread.ManagedThreadId);
            string returnValue = amc.EndInvoke(out threadId, result);

            Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".", threadId, returnValue);
        }
예제 #34
0
        public static void Main_Outdated()
        {
            // 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);


            /* //1.使用 EndInvoke 等待异步调用
             * // Call EndInvoke to wait for the asynchronous call to complete,
             * // and to retrieve the results.
             * string returnValue = caller.EndInvoke(out threadId, result);*/


            /*//2.使用 WaitHandle 等待异步调用
             * // Wait for the WaitHandle to become signaled.
             * result.AsyncWaitHandle.WaitOne();//
             * // Perform additional processing here.
             * Console.WriteLine("This is additional process");
             * // Call EndInvoke to retrieve the results.
             * string returnValue = caller.EndInvoke(out threadId, result);
             * // Close the wait handle.
             * result.AsyncWaitHandle.Close();*/


            //3.对异步调用的完成情况进行轮询
            // 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("The call executed on thread {0}, with return value \"{1}\".",
                              threadId, returnValue);
        }
예제 #35
0
        static void CallbackMethod(IAsyncResult ar)
        {
            AsyncResult       result = (AsyncResult)ar;
            AsyncMethodCaller caller = (AsyncMethodCaller)result.AsyncDelegate;

            string formatString = (string)ar.AsyncState;

            int threadId = 0;

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

            Console.WriteLine(formatString, threadId, returnValue);
        }
예제 #36
0
 private void AsyncCallback(IAsyncResult ar)
 {
     try
     {
         AsyncResult       result = (AsyncResult)ar;
         AsyncMethodCaller caller = (AsyncMethodCaller)result.AsyncDelegate;
         caller.EndInvoke(ar);
     }
     catch (Exception ex)
     {
         _logger.LogError(ex, "callback from email failed");
     }
 }
예제 #37
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();
        }
예제 #38
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;
        }
예제 #39
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);
        }
예제 #40
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
        }
예제 #41
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;

        }
예제 #42
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();
        }
        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);
            }
        }
예제 #44
0
        //WaitHandle による非同期呼び出しの待機
        static void BlockingWaitHandle()
        {
            // スレッドID保存用の変数を宣言
            int threadId;

            //AsyncDemoクラスをインスタンス化
            AsyncDemo ad = new AsyncDemo();

            //AsyncDemoのデリゲート型を使用してデリゲートを作成
            AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);

            // デリゲートのBeginInvokeを使用してThreadPoolで処理を開始
            // 引数#1はデリゲートの引数1引数#2はデリゲートの第二引数
            // #3,コールバック関数を利用する場合、#4はコールバック関数の引数
            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);
        }