Esempio n. 1
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));
        }
Esempio n. 2
0
        /// <summary>
        /// 校验http和本地数据库数据
        /// </summary>
        /// <param name="Lpn"></param>
        /// <param name="Container"></param>
        private void SelectLpnCon(string Lpn, string Container)
        {
            SetMessage_Action?.Invoke("SelectLpnCon[函数|Log|识别完成,数据开始处理]");

            //优先置空车牌和箱号
            NewLpn          = string.Empty;
            UpdateLpn       = string.Empty;
            Containernumber = string.Empty;

            Calculation_In();                     //统计入闸

            if (Lpn != null || Container != null) //字段其中一个不为空就查询服务器
            {
                SetMessage_Action?.Invoke("SelectDataBase[函数|Log|开始查询本地数据库]");

                string[] Head = { Lpn, Container };                                                //组合显示车牌和箱号
                SelectDataBase?.BeginInvoke(Lpn, Container, "", One_SelectDataBaseCallBack, Head); //查询数据库
            }
            else//没有识别到数据
            {
                bool IsOpenDoor        = false;                      //是否开闸
                var  LedShowDataResult = new string[] { "*", "*", "*", "*", "*", Working_NoOCRresult };
                LedShow(LedShowDataResult, IsOpenDoor);
            }
        }
Esempio n. 3
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);

        }
 // 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?
 }
Esempio n. 5
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);

        }
Esempio n. 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);
 }
Esempio n. 7
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;
     }
 }
Esempio n. 8
0
        static void Main(string[] args)
        {
            var action = new Func <int>(CalculateSophisticNumber);
            //action();

            var result = action?.BeginInvoke(null, null);

            Console.WriteLine(result);
            Console.WriteLine("ГЛАВНЫЙ ПОТОК ЗАВЕРШИЛ РАБОТУ");
        }
Esempio n. 9
0
        /// <summary>
        /// Gets a basic representation of a user
        /// </summary>
        public MatrixUser GetPerson(string id)
        {
            if (_cp.Client == null)
            {
                return(null);
            }
            Func <string, MatrixUser> get = _cp.Client.GetUser;
            var ar = get?.BeginInvoke(id, null, null);

            return(get.EndInvoke(ar));
        }
 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);
     }
 }
Esempio n. 11
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 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();
 }
Esempio n. 14
0
        public IAsyncResult Execute <T1, T2>(Func <T1, T2> executeCode, T1 para, Action <T2> callback)
        {
            IAsyncResult result = executeCode?.BeginInvoke(para, delegate(IAsyncResult ar)
            {
                T2 ret = default(T2);
                if (executeCode != null)
                {
                    ret = executeCode.EndInvoke(ar);
                }
                Invoke <T2>(callback, ret);
            }, null);

            return(result);
        }
 /// <summary>
 /// 校验http和本地数据库数据
 /// </summary>
 /// <param name="Lpn"></param>
 /// <param name="Container"></param>
 private void SelectLpnCon(string Lpn, string Container)
 {
     if (Lpn != null || Container != null)   //字段其中一个不为空就查询服务器
     {
         string[] Head = { Lpn, Container }; //组合显示车牌和箱号
         if (HttpSwitch)                     //是否查询远端服务器
         {
             HttpPostAction?.BeginInvoke(Passtime.ToString("yyyyMMddhhmmss"), Lpn, Container, SelectHttpCallBack, Head);
         }
         else
         {
             SelectDataBase?.BeginInvoke(Lpn, Container, "", this.SelectDataBaseCallBack, Head);//查询数据库
         }
     }
     else//没有识别到数据
     {
         bool IsOpenDoor        = false;                      //是否开闸
         var  LedShowDataResult = new string[] { "*", "*", "*", "*", "*", Working_NoOCRresult };
         LedShow(LedShowDataResult, IsOpenDoor);
     }
     NewLpn          = string.Empty;
     UpdateLpn       = string.Empty;
     Containernumber = string.Empty;
 }
        /// <summary>
        /// 查询远端服务器回调函数
        /// </summary>
        /// <param name="ar"></param>
        private void SelectHttpCallBack(IAsyncResult ar)
        {
            var Head       = (string[])ar.AsyncState;
            var HttpResult = HttpPostAction.EndInvoke(ar);//回调返回数据

            //HttpResult = @"{{""error_code"":""AE0000"",""error_desc"":""The request handled successful."",""result"":{{""resultList"":""Y"",""status"":"""",""visito"":"""",""ledgename"":"""",""platform"":"""",""truckNumber"":""粤B050CS"",""tranNo"":"""",""arrivedTime"":""2018 - 11 - 12 17:10:30""} } ";
            if (HttpResult != null)                                                  //http请求数据回调函数
            {
                HttpJsonSplitAction?.BeginInvoke(HttpResult, HttpResultSplit, Head); //查询远端服务器
            }
            else
            {
                SelectDataBase?.BeginInvoke(Head[0], Head[1], "", this.SelectDataBaseCallBack, Head);//查询数据库
            }
        }
Esempio n. 17
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);
 }
Esempio n. 18
0
        private void FormPaintBoard_Load(object sender, EventArgs e)
        {
            check              = "否";
            this.tableHandler += new ReadDataTableHandler(getData);
            this.chartHandler += new DrawChartUiHandler(drawUi);

            Func <string> funStr = getDataView;
            IAsyncResult  result = funStr.BeginInvoke(new AsyncCallback(other), null);

            timeChange = 1;

            System.Timers.Timer t = new System.Timers.Timer(1000 * 60 * timeChange);
            t.Elapsed  += new System.Timers.ElapsedEventHandler(refreData);
            t.AutoReset = true;
            t.Enabled   = true;
        }
Esempio n. 19
0
        /// <summary>
        /// Asynchronous delegate
        /// </summary>
        internal static void Prog11()
        {
            Func <string, int> deleg = new Func <string, int>((string input) =>
            {
                return(input.Length);
            });

            AsyncCallback action = (IAsyncResult input) =>
            {
                Func <string, int> target = (Func <string, int>)input.AsyncState;
                int result = target.EndInvoke(input);
                Console.WriteLine(result);
            };                                                                          // BeginInvoke -> elindítja a szál aszinkron futását, megadható egy callback, amit a futás végén meghív

            IAsyncResult resuilt = deleg.BeginInvoke("input", action, deleg);           // EndInvoke -> bevárja a resultot (ha még nincs kész), megkapja a resultot
        }
        static void Main(string[] args)
        {
            Func <int, int, int> sum = (m, n) =>
            {
                Console.WriteLine("Sum Invoked on thread: " + Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(10000);
                return(m + n);
            };
            IAsyncResult r = sum.BeginInvoke(10, 18, Completed, "Thanks Boss");

            while (!IsDone)
            {
                Console.WriteLine("Working on Main(), Thread Id: " + Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(1000);
            }
        }
Esempio n. 21
0
        ToTask <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, TResult>(

            this Func <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, TResult> @this,
            T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15, T16 arg16,
            AsyncCallback asyncCallback = null,
            object state = null,
            TaskCreationOptions taskCreationOptions = default(TaskCreationOptions),
            TaskScheduler taskScheduler             = null)
        {
            return(await Task <TResult> .Factory.FromAsync(
                       @this.BeginInvoke(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, asyncCallback, state),
                       @this.EndInvoke,
                       taskCreationOptions,
                       taskScheduler ?? TaskScheduler.Current ?? TaskScheduler.Default)
                   .ConfigureAwait(false));
        }
Esempio n. 22
0
        ToTask <T1, T2, T3, T4, T5, TResult>(

            this Func <T1, T2, T3, T4, T5, TResult> @this,
            T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5,
            AsyncCallback asyncCallback = null,
            object state = null,
            TaskCreationOptions taskCreationOptions = default(TaskCreationOptions),
            TaskScheduler taskScheduler             = null)
        {
            return(await Task <TResult> .Factory.FromAsync(
                       @this.BeginInvoke(arg1, arg2, arg3, arg4, arg5, asyncCallback, state),
                       @this.EndInvoke,
                       taskCreationOptions,
                       taskScheduler ?? TaskScheduler.Current ?? TaskScheduler.Default)
                   .ConfigureAwait(false));
        }
Esempio n. 23
0
        protected override IAsyncResult BeginExecute(
            AsyncCodeActivityContext context,
            AsyncCallback callback, object state)
        {
            CalcShippingAsyncArgs parameters = new CalcShippingAsyncArgs
            {
                Weight     = Weight.Get(context),
                OrderTotal = OrderTotal.Get(context),
                ShipVia    = ShipVia.Get(context),
            };

            Func <CalcShippingAsyncArgs, Decimal> asyncWork = a => Calculate(a);

            context.UserState = asyncWork;
            return(asyncWork.BeginInvoke(parameters, callback, state));
        }
        private void btnAsyncDelegate2_Click(object sender, EventArgs e)
        {
            //
            //非阻塞的方式执行异步委托
            //

            //定义一个委托
            Func <string, int> method = Work;
            IAsyncResult       cookie = method.BeginInvoke("test", Done, method);

            Console.ReadLine();
            //你也可以在调用BeginInvoke的时候指定一个回调方法,
            //这个方法会在异步委托结束的时候自动调用。
            //这样异步委托就像是一个后台线程一样自动执行,不需要主线程等待。
            //只需要在BeginInvoke的时候做一些额外的操作即可实现这种操作。
        }
Esempio n. 25
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);
 }
        public void FromAsyncBeginMethod_DirectResult()
        {
            bool result           = false;
            bool continuationTest = false;

            Func <int, int> func = (i) => { result = true; return(i + 3); };
            Task <int>      task = factory.FromAsync <int> (func.BeginInvoke(1, delegate { }, null), func.EndInvoke);
            var             cont = task.ContinueWith(_ => continuationTest = true, TaskContinuationOptions.ExecuteSynchronously);

            task.Wait();
            cont.Wait();

            Assert.IsTrue(result);
            Assert.IsTrue(continuationTest);
            Assert.AreEqual(4, task.Result);
        }
 public Future(Func <TValue> function, Action <TValue> callback = null)
 {
     this._getter = this._WaitForValueCreation;
     function.BeginInvoke(asyncResult => {
         try {
             this._value = function.EndInvoke(asyncResult);
             callback?.Invoke(this._value);
             Interlocked.Exchange(ref this._getter, this._GetRawValue);
         } catch (Exception exception) {
             this._exception = exception;
             Interlocked.Exchange(ref this._getter, this._ThrowException);
         } finally {
             ((ManualResetEventSlim)asyncResult.AsyncState).Set();
         }
     }, this._HasValueAlready);
 }
Esempio n. 28
0
        static void Main(string[] args)
        {
            Console.WriteLine("主1====" + DateTime.Now.ToString() + "================" + Thread.CurrentThread.ManagedThreadId);
            Func <string> func = new Func <string>(DoTestFun);

            Console.WriteLine("func.Method---" + func.Method);
            var ar = func.BeginInvoke(null, null);

            Console.WriteLine("主2====" + DateTime.Now.ToString() + "================" + Thread.CurrentThread.ManagedThreadId);

            var result = func.EndInvoke(ar);

            Console.WriteLine("主3====" + DateTime.Now.ToString() + "================" + Thread.CurrentThread.ManagedThreadId);
            Console.WriteLine("result:" + result);
            Console.ReadKey();
        }
Esempio n. 29
0
        /// <summary>
        /// </summary>
        /// <param name="update"></param>
        public static void CloseApplication(bool update = false)
        {
            Application.Current.MainWindow.WindowState = WindowState.Normal;
            SettingsHelper.Save(update);
            foreach (PluginInstance pluginInstance in App.Plugins.Loaded.Cast <PluginInstance>().Where(pluginInstance => pluginInstance.Loaded))
            {
                pluginInstance.Instance.Dispose(update);
            }

            Func <bool> export = () => SavedlLogsHelper.SaveCurrentLog(false);

            export.BeginInvoke(
                delegate {
                CloseDelegate(update);
            }, export);
        }
Esempio n. 30
0
        private void ServiceConnector(object source, Service.Connector.ServiceConnectorArgs e)
        {
            if (e == null)
            {
                return;
            }

            IRunDevice runDevice = this.DeviceManager.GetDeviceFromCode(e.ServiceToDevice.DeviceCode);

            if (runDevice != null)
            {
                Func <IFromService, IServiceToDevice, object> serviceConnctor = runDevice.RunServiceConnector;
                ServiceConnectorToken token = new ServiceConnectorToken(e.FromService.ServiceKey, serviceConnctor);
                serviceConnctor.BeginInvoke(e.FromService, e.ServiceToDevice, new AsyncCallback(ServiceConnectorCallback), token);
            }
        }
Esempio n. 31
0
 public static void DoAsync <TInput, TResult>(this Func <TInput, TResult> f, TInput arg, Action <TResult> callback)
 {
     //f.BeginInvoke(arg, x => callback(f.EndInvoke(x)), null);
     f.BeginInvoke(arg, x =>
     {
         if (callback != null)
         {
             callback(f.EndInvoke(x));
         }
         else
         {
             f.EndInvoke(x);
         }
     }
                   , null);
 }
Esempio n. 32
0
        private void DeviceConnector(object source, Device.Connector.DeviceConnectorArgs e)
        {
            if (e == null)
            {
                return;
            }

            IRunDevice runDevice = this.DeviceManager.GetDeviceFromCode(e.DeviceToDevice.DeviceCode);

            if (runDevice != null)
            {
                Func <IFromDevice, IDeviceToDevice, object> deviceConnctor = runDevice.RunDeviceConnector;
                DeviceConnectorToken token = new DeviceConnectorToken(e.FromDevice.DeviceID, deviceConnctor);
                deviceConnctor.BeginInvoke(e.FromDevice, e.DeviceToDevice, new AsyncCallback(DeviceConnectorCallback), token);
            }
        }
Esempio n. 33
0
        static void Main()
        {
            var myDelegate = new Func <int, int, int>(Add);

            // Так как класс делегата сообщается с методами, которые принимают два целочисленных параметра, метод BeginInvoke также
            // начинает принимать два дополнительных параметра, кроме двух последних постоянных аргументов.
            IAsyncResult asyncResult = myDelegate.BeginInvoke(1, 2, null, null);

            // Ожидание завершения асинхронной операции и получение результата работы метода.
            int result = myDelegate.EndInvoke(asyncResult);

            Console.WriteLine("Результат = " + result);

            // Delay.
            Console.ReadKey();
        }
Esempio n. 34
0
        protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
        {
            var pushNotification = PushNotification.Get(context);
            var contentListPath  = ContentListPath.Get(context);

            if (string.IsNullOrEmpty(contentListPath))
            {
                SnLog.WriteError("ExchangePoller activity: ContentList path is empty.", categories: ExchangeHelper.ExchangeLogCategory);
                return(null);
            }

            var GetMessageInfosDelegate = new Func <bool, string, EmailMessage[]>(GetMessageInfos);

            context.UserState = GetMessageInfosDelegate;
            return(GetMessageInfosDelegate.BeginInvoke(pushNotification, contentListPath, callback, state));
        }
Esempio n. 35
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);
 }
Esempio n. 36
0
        /// <summary>
        /// </summary>
        /// <param name="pSignatures"> </param>
        /// <param name="scanAllMemoryRegions"></param>
        public void LoadOffsets(IEnumerable <Signature> pSignatures, bool scanAllMemoryRegions = false)
        {
            IsScanning = true;

            Func <bool> scanningFunc = delegate
            {
                var sw = new Stopwatch();
                sw.Start();
                if (MemoryHandler.Instance.ProcessModel?.Process == null)
                {
                    return(false);
                }
                var signatures = new List <Signature>(pSignatures);

                if (scanAllMemoryRegions)
                {
                    LoadRegions();
                }

                if (signatures.Any())
                {
                    foreach (var signature in signatures)
                    {
                        if (signature.Value == string.Empty)
                        {
                            // doesn't need a signature scan
                            Locations[signature.Key] = signature;
                            continue;
                        }
                        signature.Value = signature.Value.Replace("*", "?"); // allows either ? or * to be used as wildcard
                    }
                    signatures.RemoveAll(a => Locations.ContainsKey(a.Key));

                    FindExtendedSignatures(signatures, scanAllMemoryRegions);
                }

                sw.Stop();

                MemoryHandler.Instance.RaiseSignaturesFound(Logger, Locations, sw.ElapsedMilliseconds);

                IsScanning = false;

                return(true);
            };

            scanningFunc.BeginInvoke(null, null);
        }
        private void ProcessSample()
        {
            var openFileDialog = new OpenFileDialog
            {
                InitialDirectory = Path.Combine(Common.Constants.CachePath, "Logs"),
                Multiselect      = false,
                Filter           = "XML Files (*.xml)|*.xml"
            };

            openFileDialog.FileOk += delegate
            {
                var count     = 0;
                var sampleXml = XDocument.Load(openFileDialog.FileName);
                var items     = new Dictionary <int, string[]>();
                foreach (var xElement in sampleXml.Descendants()
                         .Elements("Entry"))
                {
                    var xKey       = (string)xElement.Attribute("Key");
                    var xBytes     = (string)xElement.Element("Bytes");
                    var xLine      = (string)xElement.Element("Line");
                    var xTimeStamp = (string)xElement.Element("TimeStamp");
                    if (String.IsNullOrWhiteSpace(xKey) || String.IsNullOrWhiteSpace(xLine))
                    {
                        continue;
                    }
                    items.Add(count, new[]
                    {
                        xKey, xLine, xTimeStamp, xBytes
                    });
                    ++count;
                }
                Func <bool> func = delegate
                {
                    foreach (var chatLogEntry in items.Select(item => new ChatLogEntry
                    {
                        Code = item.Value[0],
                        Line = item.Value[1].Replace("  ", " ")
                    }))
                    {
                        EventParser.Instance.ParseAndPublish(chatLogEntry);
                    }
                    return(true);
                };
                func.BeginInvoke(null, null);
            };
            openFileDialog.ShowDialog();
        }
Esempio n. 38
0
        static void Main(string[] args)
        {
            Console.WriteLine("Before call");
            Action o = display;

            o();
            Console.WriteLine("After call");

            Console.WriteLine("Before call");
            Action o = display;

            o.BeginInvoke(null, null);
            Console.WriteLine("After call");


            Console.WriteLine("Before call");
            Action <string> o2 = display;

            o2.BeginInvoke("Vipul", null, null);
            Console.WriteLine("After call");

            Console.WriteLine("Before");
            Func <string, string> o1 = display;
            demo d = new demo();

            o1.BeginInvoke("vipul zope", delegate(IAsyncResult ar)
            {
                Console.WriteLine("This is callback function");
                string name = o1.EndInvoke(ar);
                Console.WriteLine("name is " + name);
            }, null);

            demo d = new demo();

            Console.WriteLine("Before addition");
            Func <int, int, int> fobj = display;

            fobj.BeginInvoke(10, 20, new AsyncCallback(delegate(IAsyncResult ar)
            {
                Console.WriteLine("This is callback function");
                int a = fobj.EndInvoke(ar);
                Console.WriteLine(a);
            }), null);
            Console.WriteLine("After addition");

            Console.ReadLine();
        }
Esempio n. 39
0
        /// <summary>
        /// </summary>
        public static void CacheSoundFiles()
        {
            try {
                if (!Directory.Exists(Constants.SoundsPath))
                {
                    Directory.CreateDirectory(Constants.SoundsPath);
                }

                List <FileInfo> soundFiles = new List <FileInfo>();
                List <string>   filters    = new List <string> {
                    "*.wav",
                    "*.mp3",
                };
                foreach (var filter in filters)
                {
                    IEnumerable <FileInfo> files = Directory.GetFiles(Constants.SoundsPath, filter, SearchOption.AllDirectories).Select(file => new FileInfo(file));
                    soundFiles.AddRange(files);
                }

                Func <bool> cacheSounds = delegate {
                    foreach (FileInfo soundFile in soundFiles)
                    {
                        if (soundFile.DirectoryName == null)
                        {
                            continue;
                        }

                        var baseKey = soundFile.DirectoryName.Replace(Constants.SoundsPath, string.Empty);
                        var key     = string.IsNullOrWhiteSpace(baseKey)
                                      ? soundFile.Name
                                      : $"{baseKey.Substring(1)}\\{soundFile.Name}";
                        if (SoundFileKeys(false).Contains(key))
                        {
                            continue;
                        }

                        TryGetSetSoundFile(key);
                    }

                    return(true);
                };
                cacheSounds.BeginInvoke(delegate { }, cacheSounds);
            }
            catch (Exception ex) {
                Logging.Log(Logger, new LogItem(ex, true));
            }
        }
Esempio n. 40
0
        public void yibu()
        {
            Func <string, int> func = (s) =>
            {
                Thread.Sleep(3000);
                return(s.Length);
            };

            func.BeginInvoke("123", (res) =>
            {
                while (!res.IsCompleted)
                {
                    Thread.Sleep(100);
                }
                var len = func.EndInvoke(res);
            }, null);
        }
Esempio n. 41
0
 public string GetReverseDNS(string ip, int timeout)
 {
     try
     {
         Func <IPAddress, IPHostEntry> callback = s => Dns.GetHostEntry(s);
         var result = callback.BeginInvoke(IPAddress.Parse(ip), null, null);
         if (!result.AsyncWaitHandle.WaitOne(timeout, false))
         {
             return("");
         }
         return(callback.EndInvoke(result).HostName);
     }
     catch (Exception)
     {
         return("");
     }
 }
Esempio n. 42
0
        public static ConsoleKeyInfo?ReadKey(TimeSpan timeout)
        {
            Func <ConsoleKeyInfo> readKey = System_Console.ReadKey;

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

            result.AsyncWaitHandle.WaitOne(timeout);

            if (!result.IsCompleted)
            {
                return(null);
            }

            var keyRead = readKey.EndInvoke(result);

            return(keyRead);
        }
Esempio n. 43
0
        static void Main(string[] args)
        {
            Func <int, int, int> myDelegate  = new Func <int, int, int>(Sum);
            IAsyncResult         asyncResult = myDelegate.BeginInvoke(1, 2, null, null);

            Console.WriteLine("Асинхронный метод запущен. Метод Main продолжает работать");

            while (!asyncResult.IsCompleted)
            {
                Thread.Sleep(100);
                Console.Write(".");
            }
            int result = myDelegate.EndInvoke(asyncResult);

            Console.WriteLine("Результат " + result);
            Console.ReadKey();
        }
Esempio n. 44
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();
        }
Esempio n. 45
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);
        }
Esempio n. 49
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));
        }
Esempio n. 50
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);
        }
		/// <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;
		}
        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);
            }
        }
 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);
 }
Esempio n. 54
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);
        }
 public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
 {
     var function = new Func<object>(() => { return null; });
     return function.BeginInvoke(callback, state);
 }
Esempio n. 56
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);
 }
Esempio n. 57
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);
 }
Esempio n. 58
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);
 }
Esempio n. 59
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);
 }
Esempio n. 60
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);
            
        }