Example #1
0
        static void ScanDouble()
        {
            // Delegates anlegen
            var dg1 = new Func<long, long, IEnumerable<long>>(mko.Algo.NumberTheory.PrimeFactors.scan);
            var dg2 = new Func<long, long, IEnumerable<long>>(mko.Algo.NumberTheory.PrimeFactors.scan);
            var dg3 = new Func<long, long, IEnumerable<long>>(mko.Algo.NumberTheory.PrimeFactors.scan);
            var dg4 = new Func<long, long, IEnumerable<long>>(mko.Algo.NumberTheory.PrimeFactors.scan);


            // Methoden asynchron mittels Delegates starten
            var ares1=  dg1.BeginInvoke(1, 2500000, null, null);
            var ares2=  dg2.BeginInvoke(2500001, 5000000, null, null);
            var ares3 = dg3.BeginInvoke(5000001, 75000000, null, null);
            var ares4 = dg4.BeginInvoke(7500001, 10000000, null, null);

            while (!ares1.IsCompleted && !ares2.IsCompleted && !ares3.IsCompleted && !ares4.IsCompleted)
            {
                Debug.Write(".");
                System.Threading.Thread.Sleep(200);
            }

            //ares1.AsyncWaitHandle.WaitOne();

            var res1 = dg1.EndInvoke(ares1);
            var res2 = dg2.EndInvoke(ares2);

        }
Example #2
0
        private void button1_Click(object sender, EventArgs e)
        {
            // the inputs
            int x = 2;

            // the "thread" or work to be "BeginInvoked"
            var dlg = new Func<int, int>(
                param =>
                {
                    // put in a sleep just for fun...
                    System.Threading.Thread.Sleep(500);

                    // note that, while we COULD have referenced "x" here, we are NOT...
                    // pretend this lives somewhere else... or is even a web request or something.
                    return param * 2;
                });

            // "BeginInvoke" will spawn a new ThreadPool thread to do the work for us
            var iar = dlg.BeginInvoke(
                // this corresponds to the "param" in the delegate above
                x,

                // who gets called when the work is completed
                Callback,

                // "AsyncState" - used to pass additional information around
                // By convention, the convention was to usually use an object array
                // I'd recommend using a Tuple now for more "strong typed ness"
                // - first parameter here is the actual delegate (lambda)
                // - second parameter here is the input (why? you'll see in a little bit...)
                // Alternatively, you can use a custom object here... depends on the consumer as far as which you'd want to use
                new Tuple<Func<int, int>, int>(dlg, x));
        }
 // See also http://stackoverflow.com/questions/1047662/what-is-asynccallback for this ugly callback model.
 static IAsyncResult beginSimulatedDatabaseRequest(AsyncCallback callback)
 {
     // simulate long running I/O here, e.g. a DB request
       var func = new Func<int>(() => {
     System.Threading.Thread.Sleep(3000);
     return ++requestX; // not threadsafe, whatever
       });
       return func.BeginInvoke(callback, func); // which thread will this execute on? A threadpool?
 }
Example #4
0
        static void Main(string[] args)
        {
            Func<int, int, int> additionDel = new Func<int, int, int>(Addition);
            int ret = additionDel.Invoke(1, 2);
            Console.WriteLine("From Sync invoke " + ret);
            object state = new Object();
            IAsyncResult _asyncresult = additionDel.BeginInvoke(1,2,null, null);
            //calling thread blocks until endInvokecompletes
            ret= additionDel.EndInvoke(_asyncresult);
            Console.WriteLine("From Aynsc EndInvoke " + ret);

             _asyncresult = additionDel.BeginInvoke(1, 2, new AsyncCallback(PrintCallBack), null);
            // ret = additionDel.EndInvoke(_asyncresult);
            // Console.WriteLine("From Aynsc EndInvoke On asyncCallback" + ret);

             Thread.Sleep(5000);

        }
Example #5
0
 public override void Run()
 {
     if (Enable && !connecting && !GlobalVariables.IsConnected() &&
         Kernel.GetInstance().ActionControl.CanPerformAction(ActionControlType.LOGIN))
     {
         var func = new Func<String, String, String, bool>(Kernel.GetInstance().Client.Login.Login);
         func.BeginInvoke(Account, Password, CharacterName, new AsyncCallback(LoginCallback), func);
         connecting = true;
     }
 }
Example #6
0
 /// AsynchronouseProngraingModel
 void apm()
 {
     before_work();
     var method = new Func<double>(() => { busy_work(); return 0; });
     method.BeginInvoke(ar =>
     {
         var result = method.EndInvoke(ar);// get return value
         this.BeginInvoke((Action)(() => { after_work(); }));
     }, null);
 }
Example #7
0
        IEnumerator<IAsyncCall> DatabaseTask()
        {
            button1.Enabled = false;

            AsyncCall<int> call = new AsyncCall<int>();

            Func slow = new Func(DarnSlowDatabaseCall);

            yield return call.WaitOn(cb => slow.BeginInvoke(cb, null)) & slow.EndInvoke;

            textBox1.Text = "db task returned " + call.Result + "\r\n";
            button1.Enabled = true;
        }
 public void TimeoutTest()
 {
     // Arrange.
     var func = new Func<ProcessExecutionResult>(() => ProcessRunner.RunProcess("cmd.exe", PauseArguments, Timeout));
     // Act.
     var result = func.BeginInvoke((a) => { }, null);
     result.AsyncWaitHandle.WaitOne(Timeout + AdditionalTimeout);
     // Assert.
     if (result.IsCompleted)
     {
         func.EndInvoke(result);
     }
 }
        public MainWindow()
        {
            InitializeComponent();

            worker.ConnectionStatus += status => this.GuiAsync(() => ConnectionStatus(status));
            worker.Processed += (a, b) => this.GuiAsync(() => Worker_Processed(a, b));

            Processed += (i) => this.GuiAsync(() => MainWindow_Processed(i));

            Func<int> func = new Func<int>(GetAvailableWorkThreads);
            IAsyncResult asyncResult;
            asyncResult = func.BeginInvoke(null, null);
        }
 public void TimeoutKillTest()
 {
     // Arrange.
     var func = new Func<ProcessExecutionResult>(() => ProcessRunner.RunProcess("cmd.exe", PauseArguments, Timeout));
     // Act.
     var result = func.BeginInvoke((a) => { }, null);
     result.AsyncWaitHandle.WaitOne();
     // Assert.
     if (Process.GetCurrentProcess().GetChildProcesses().Any())
     {
         Assert.Fail();
     }
     Assert.Pass();
 }
Example #11
0
 /// <summary>异步传参数
 /// </summary>
 /// <param name="age"></param>
 public static void ybpara(int age)
 {
     //异步执行
     Func<people, string> FuncAsy = new Func<people, string>((pp) =>
     {
         return pp.Name;
     }
     );
     FuncAsy.BeginInvoke(new people("小李" + age, age), resual =>
     {
         //异步执行,从回调函数中获取返回结果
         Console.WriteLine(">>>>:{0}", FuncAsy.EndInvoke(resual));
         Console.WriteLine(">>>>:{0} end", age);
     }, null);
 }
Example #12
0
 /// <summary>异步
 /// </summary>
 /// <param name="age"></param>
 public static void yb(int age)
 {
     //异步执行
     Func<string> FuncAsy = new Func<string>(() =>
     {
         people tPeo = new people("异步小李", age);
         return tPeo.ToString();
     }
     );
     FuncAsy.BeginInvoke(resual =>
     {
         //异步执行,从回调函数中获取返回结果
         Console.WriteLine(">>>>:{0}", FuncAsy.EndInvoke(resual));
         Console.WriteLine(">>>>:{0} end", age);
     }, null);
 }
Example #13
0
 public static void LoadAsync(string filename, Action<IStorableContent, Exception> loadingCompletedCallback) {
   if (instance == null) throw new InvalidOperationException("ContentManager is not initialized.");
   var func = new Func<string, IStorableContent>(instance.LoadContent);
   func.BeginInvoke(filename, delegate(IAsyncResult result) {
     Exception error = null;
     IStorableContent content = null;
     try {
       content = func.EndInvoke(result);
       content.Filename = filename;
     }
     catch (Exception ex) {
       error = ex;
     }
     loadingCompletedCallback(content, error);
   }, null);
 }
Example #14
0
        static void Main(string[] args)
        {
            Func<string, string> cmdPrint = null;

            cmdPrint = new Func<string, string>(
                    x=> { Thread.Sleep(10000); return  "Hola " + x;}
            );

            var cb = new AsyncCallback(delegate(IAsyncResult result) {
                var del = result.AsyncState as Func<string, string>;
                var men = del.EndInvoke(result);
                Console.WriteLine(men);
            });
            cmdPrint.BeginInvoke("Juan", cb, cmdPrint);
            Otra();
            Console.ReadLine();
        }
Example #15
0
        public static void Execute(Action<bool> isBusy, Func<AsyncCallResult> operation, Action<AsyncCallResult> resultHandler)
        {
            if (isBusy == null)
                throw new ArgumentNullException("isBusy");

            if (operation == null)
                throw new ArgumentNullException("operation");

            if (resultHandler == null)
                throw new ArgumentNullException("resultHandler");

            // Get current thread dispatcher
            Dispatcher dispatcher = Dispatcher.CurrentDispatcher;

            // Set the busy indicator
            isBusy.Invoke(true);

            // Crate an async operation delegate instance.
            Func<Action<bool>, AsyncCallResult> asyncOperation = new Func<Action<bool>, AsyncCallResult>((a) => { return operation.Invoke(); });

            // Start async operation.
            var operationHandler =  asyncOperation.BeginInvoke(isBusy, (ar) =>
            {
                // Retrieve the delegate instance.
                var dlgt = (Func<Action<bool>, AsyncCallResult>)ar.AsyncState;

                // Call EndInvoke to retrieve the results.
                var ret = dlgt.EndInvoke(ar);

                // Refresh UI through dispatcher
                dispatcher.BeginInvoke(DispatcherPriority.Send, (SendOrPostCallback)delegate
                {
                    try
                    {
                        resultHandler.Invoke(ret);
                    }
                    finally
                    {
                        isBusy.Invoke(false);
                    }
                }, null);

            }, asyncOperation);
        }
        /**
         * Begin asynchronous execution of a query.
         * @param query The query to execute. Can be one of the following:
         * <ul>
         * <li><b>randomize</b> Randomizes a pseudonym. parameters[0] must be the pseudonym to randomize.
         * <li><b>getEP</b> Returns an encrypted pseudonym. parameters[0] must be the User ID, parameters[0] the SP ID.
         * <li><b>getEP</b> Returns a polymorphic pseudonym. parameters[0] must be the User ID.
         * </ul>
         * @param parameters The parameters for the query.
         * @param callback The delegate to call when execution is finished.
         * @param state Not used.
         * @return IAsyncResult for the asynchronous execution.
         */
        public IAsyncResult BeginExecuteQuery(string query, string[] parameters, AsyncCallback callback, object state)
        {
            PolyPseudWorker worker = new PolyPseudWorker(parameters, config["y_k"], config["connectionString"], config["pseudonymProviderUrl"]);

            switch(query)
            {
                case "randomize":
                    func = new Func<string[][]>(worker.Randomize);
                    return func.BeginInvoke(callback, state);
                case "getEP":
                    func = new Func<string[][]>(worker.GetEP);
                    return func.BeginInvoke(callback, state);
                case "getPP":
                    func = new Func<string[][]>(worker.GetPP);
                    return func.BeginInvoke(callback, state);
                default:
                    throw new ArgumentException(String.Format("The query '{0}' is not recognized.", query));
            }
        }
        static void Main(string[] args)
        {
            Func<int, int, string> del = new Func<int, int, string>((a, b) =>
            {
                Thread.Sleep(1111);
                Console.WriteLine("该委托调用的线程Id是" + Thread.CurrentThread.ManagedThreadId);
                return (a + b).ToString();
                //打印当前线程Id
            });
            #region 无回调函数的委托异步调用

            ////该BeginInvoke是vs反编译出来的
            ////传入参数: 方法传入参数若干,回调函数,回调函数参数
            ////返回值:IAsyncResult表示异步状态的接口
            //IAsyncResult result = del.BeginInvoke(3, 4, null, null);
            ////内部原理:用线程池中的一个线程调用该方法

            ////EndInvoke 方法检索异步调用的结果。 在调用 BeginInvoke 之后随时可以调用该方法。 如果异步调用尚未完成,则 EndInvoke 会一直阻止调用线程,直到异步调用完成。
            //string resultValue = del.EndInvoke(result);
            //Console.WriteLine("委托结果是{0},当前线程是{1}", resultValue, Thread.CurrentThread.ManagedThreadId);

            #endregion

            #region 有回调函数的委托异步调用

            #region 第一种调用法
            ////回调函数的执行线程与异步委托的执行线程一样
            //del.BeginInvoke(3, 4, MyAsyncCallback, "我是回调函数传入参数");
            #endregion

            #region 第二中调用法
            //把异步执行的委托作为回调函数参数
            del.BeginInvoke(3, 4, MyAsyncCallback, del);
            #endregion

            #endregion

            Console.ReadKey();
        }
        public NugetConverterService(string[] args)
        {
            InitializeComponent();
            _eventLog = new EventLog();
            if (!EventLog.SourceExists("NugetConverterService"))
            {
                EventLog.CreateEventSource("NugetConverterService", "Application");
            }
            _eventLog.Source = "NugetConverterService";
            _eventLog.Log = "Application";

            runService = () =>
            {
                Trace.TraceInformation("Nuget Converter Starting...");
                _eventLog.WriteEntry("Nuget Converter Starting...");
                var error = Ullink.NugetConverter.Program.Run(args);
                if (error != null)
                    Trace.TraceError(error);
                return error;

            };
            runService.BeginInvoke(Callback, null);
        }
Example #19
0
        private void button1_Click(object sender, EventArgs e)
        {
            // the inputs
            int inputToLongRunningOp = 2;

            // the "thread" or work to be "BeginInvoked"
            var dlg = new Func<int, int>(LongRunningOperation);

            // "BeginInvoke" will spawn a new ThreadPool thread to do the work for us
            var iar = dlg.BeginInvoke(
                // this corresponds to the "param" in the delegate above
                inputToLongRunningOp,

                // who gets called when the work is completed
                Callback,

                // "AsyncState" - used to pass additional information around
                // By convention, the convention was to usually use an object array
                // I'd recommend using a Tuple now for more "strong typed ness"
                // - first parameter here is the actual delegate (lambda)
                // - second parameter here is the input (why? you'll see in a little bit...)
                // Alternatively, you can use a custom object here... depends on the consumer as far as which you'd want to use
                new Tuple<Func<int, int>, int>(dlg, inputToLongRunningOp));
        }
 private void btnBurnClick(object sender, RoutedEventArgs e)
 {
     var asyncBurn = new Func<IEnumerable<String>, IEnumerable<SyndicationItem>>((feeds) => Burn(feeds));
     asyncBurn.BeginInvoke(new[] { Common.Feeds.Digg, Common.Feeds.Meneame }, BurnEnd, asyncBurn);
 }
Example #21
0
        public void StartSearch()
        {
            _guiStateArgs.MenuEnabled = false;
            GuiStateUpdate(this, _guiStateArgs);
            SearchParams searchParams = _parentLogTabWin.SearchParams;
            if ((searchParams.isForward || searchParams.isFindNext) && !searchParams.isShiftF3Pressed)
            {
                searchParams.currentLine = dataGridView.CurrentCellAddress.Y + 1;
            }
            else
            {
                searchParams.currentLine = dataGridView.CurrentCellAddress.Y - 1;
            }

            _currentSearchParams = searchParams;    // remember for async "not found" messages

            _isSearching = true;
            _shouldCancel = false;

            StartProgressBar(dataGridView.RowCount, "Searching... Press ESC to cancel.");

            Func<SearchParams, int> searchFx = new Func<SearchParams, int>(Search);
            searchFx.BeginInvoke(searchParams, SearchComplete, null);

            RemoveAllSearchHighlightEntries();
            AddSearchHitHighlightEntry(searchParams);
        }
Example #22
0
 public IAsyncResult BeginNegation(float operand, AsyncCallback computeCallback, object state)
 {
     Func<float, float> negation = new Func<float, float>(this.Negative);
     AsyncState asyncState = new AsyncState("Negation", negation, state);
     return negation.BeginInvoke(operand,computeCallback, asyncState);
 }
Example #23
0
 public IAsyncResult BeginDivision(float right, float left, AsyncCallback computeCallBack, object state)
 {
     Func<float, float, float> division = new Func<float, float, float>(this.Division);
     AsyncState asyncState = new AsyncState("Divison", division, state);
     return division.BeginInvoke(right, left, computeCallBack, asyncState);
 }
Example #24
0
 public IAsyncResult BeginMultiplication(float right, float left, AsyncCallback computeCallBack, object state)
 {
     Func<float, float, float> multiplication = new Func<float, float, float>(this.Multiply);
     AsyncState asyncState = new AsyncState("Multiplication", multiplication, state);
     return multiplication.BeginInvoke(right, left, computeCallBack, asyncState);
 }
Example #25
0
 public IAsyncResult BeginSubtraction(float right, float left, AsyncCallback computeCallBack, object state)
 {
     Func<float, float, float> subtraction = new Func<float, float, float>(this.Subtract);
     AsyncState asyncState = new AsyncState("Subtraction",subtraction, state);
     return subtraction.BeginInvoke(right, left, computeCallBack, asyncState);
 }
Example #26
0
        /// <summary>
        /// Asynchronously Load all Files, find shortest paths and put the result into ResultItems 
        /// </summary>
        /// <param name="files"></param>
        /// <param name="uiBeforeCallback"></param>
        /// <param name="uiAfterCallback"></param>
        /// <returns>IAsyncResult</returns>
        public IAsyncResult LoadFilesAsync( IEnumerable<string> files, 
            Action<object> uiBeforeCallback = null, 
            Action<object> uiAfterCallback = null)
        {
            ResultItems.Clear();
            // Create Delegate to LoadFiles function
            Func<IEnumerable<string>, Action<object>, Action<object>, IEnumerable<ResultItem>> loadFunc =
                new Func<IEnumerable<string>, Action<object>, Action<object>, IEnumerable<ResultItem>>(LoadFiles);

            // Asnchronously invoke the delegate
            return loadFunc.BeginInvoke(files, uiBeforeCallback, uiAfterCallback, new AsyncCallback(LoadFilesCallback), loadFunc);
        }
 public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
 {
     var function = new Func<object>(() => { return null; });
     return function.BeginInvoke(callback, state);
 }
        private void postSelected(object sender, SelectionChangedEventArgs e)
        {
            Mouse.OverrideCursor = Cursors.Wait;

            if (e.AddedItems != null && e.AddedItems.Count == 1)
            {
                var selectedPost = (SyndicationItem)e.AddedItems[0];
                var asyncGetPostContents = new Func<SyndicationItem, String>((item) => GetPostContents(item));
                asyncGetPostContents.BeginInvoke(selectedPost, EndGetPostContents, asyncGetPostContents);
            }
        }
		/// <summary>
		/// Starts the task, optionally in a background thread, and waits until the task completes.
		/// </summary>
		/// <remarks>
		/// If the task is started in a background thread, the task will be terminated in the
		/// calling thread terminates. Otherwise, the calling thread will not terminate until
		/// the task completes.
		/// </remarks>
		/// <param name="p_booRunInBackground">Whether the task should be run in a background thread.</param>
		/// <param name="p_objArgs">Arguments to pass to the task execution method.</param>
		/// <returns>The return value of the task.</returns>
		/// <seealso cref="StartWait(object[])"/>
		/// <seealso cref="Start(object[])"/>
		/// <seealso cref="Start(bool, object[])"/>
		protected object StartWait(bool p_booRunInBackground, params object[] p_objArgs)
		{
			//see Start() for discussion on BeginInvoke/EndInvoke versus
			// threads
			//
			//in this method, it appears we should be using BeginInvoke/EndInvoke,
			// unlike in the Start() method. this is because it makes the most
			// sense for an exception thrown during the execution of the task to
			// bubble up the the caller of this method, which EndInvoke allows.
			// this is important for things like transactions: letting the exception
			// bubble up allows the transaction to roll back when an unhandled
			// exception is thrown in the task's code
			// with threading, this doesn't happen - at least not unless we make it.
			Func<object, object> dlg = new Func<object, object>(RunThreadedWork);
			IAsyncResult ar = dlg.BeginInvoke(p_objArgs, null, p_objArgs);
			m_objReturnValue = dlg.EndInvoke(ar);
			ar.AsyncWaitHandle.Close();

			/*
			m_areTaskEnded.Reset();
			Start(p_booRunInBackground, p_objArgs);
			m_areTaskEnded.WaitOne();*/
			return m_objReturnValue;
		}
Example #30
0
        //public delegate float Func<float,float,float>(float right, float left);
        //public delegate float Func<float,float>(float operand);

        public IAsyncResult BeginAdditon(float right, float left, AsyncCallback computeCallBack, object state)
        {
            Func<float,float,float> addition = new Func<float,float,float>(this.Add);
            AsyncState asyncState = new AsyncState("Addition", addition, state);
            return addition.BeginInvoke(right, left, computeCallBack, asyncState);
            
        }