コード例 #1
0
ファイル: Benchmark.cs プロジェクト: tmpkus/openvss
        private static double TimeCode(RunDelegate init, RunDelegate run, RunDelegate flush, int count)
        {
            int unrollCount = 10;

            if (init != null)
            {
                init();
            }
            run();
            run();
            run();
            StopWatch sw = new StopWatch();

            sw.Start();

            for (int i = 0; i < count; ++i)
            {
                run();
                run();
                run();
                run();
                run();
                run();
                run();
                run();
                run();
                run();
            }
            if (flush != null)
            {
                flush();
            }
            sw.Stop();
            return(sw.Nanoseconds / (count * unrollCount));
        }
コード例 #2
0
        /*Object Parent;
         *
         * public ProcessBaseImplThreads(Object Parent)
         * {
         *      this.Parent = Parent;
         * }*/

        public void Init(RunDelegate Delegate)
        {
            //Console.WriteLine("Init(" + Parent + ")");

            if (mainThread == null)
            {
                SemaphoreGlobal = new Semaphore(1, 1);
                SemaphoreGlobal.WaitOne();

                mainThread = Thread.CurrentThread;
                //mainMutex.WaitOne();
            }

            Semaphore = new Semaphore(1, 1);
            Semaphore.WaitOne();
            currentThread = new Thread(delegate()
            {
                Semaphore.WaitOne();
                //currentThread.Interrupt();
                Delegate();
            });

            currentThread.Start();

            //Mutex.WaitOne();
        }
コード例 #3
0
        /*Object Parent;

        public ProcessBaseImplThreads(Object Parent)
        {
            this.Parent = Parent;
        }*/
        public void Init(RunDelegate Delegate)
        {
            //Console.WriteLine("Init(" + Parent + ")");

            if (mainThread == null)
            {
                SemaphoreGlobal = new Semaphore(1, 1);
                SemaphoreGlobal.WaitOne();

                mainThread = Thread.CurrentThread;
                //mainMutex.WaitOne();
            }

            Semaphore = new Semaphore(1, 1);
            Semaphore.WaitOne();
            currentThread = new Thread(delegate()
            {
                Semaphore.WaitOne();
                //currentThread.Interrupt();
                Delegate();
            });

            currentThread.Start();

            //Mutex.WaitOne();
        }
コード例 #4
0
ファイル: Benchmark.cs プロジェクト: tmpkus/openvss
        private static void TimeAndDiscardUnusual(RunDelegate init, RunDelegate run, RunDelegate flush, int count, int samples, out double min, out double max, out double avg)
        {
            double[] times = new double[samples];

            for (int i = 0; i < times.Length; ++i)
            {
                times[i] = TimeCode(init, run, flush, count) - _overhead;
            }

            Array.Sort(times);

            // discard lowest 20% and highest 20%

            int startAt = times.Length * 20 / 100;
            int endAt   = times.Length * 80 / 100;

            max = times[startAt];
            min = times[startAt];
            avg = 0.0;
            int cnt = 0;

            for (int i = startAt; i < endAt; ++i)
            {
                max  = Math.Max(max, times[i]);
                min  = Math.Min(min, times[i]);
                avg += times[i];
                cnt++;
            }

            avg /= cnt;
        }
コード例 #5
0
        public void Run(RunDelegate d1, ExceptionDelegate d2)
        {
            if (!open || ActiveCount() >= maxSize)
            {
                throw new Exception("free pool thread count exceeded or pool closed");
            }

            Thread t = new Thread(
                delegate()
            {
                try
                {
                    d1();
                }
                catch (Exception e)
                {
                    d2(e);
                }
                finally
                {
                    lock (group)
                    {
                        group.Remove(Thread.CurrentThread);
                    }
                }
            });

            lock (group)
            {
                group.Add(t, t);
            }

            t.Start();
        }
コード例 #6
0
        public void RunCallback(IAsyncResult asyncResult)
        {
            RunDelegate runDelegate = (RunDelegate)asyncResult.AsyncState;

            Plan.SetStatus(ForecastPlanStatus.Run);
            Plan.ExecutionDate = DateTime.Today;
            _dataService.UpdateForecastPlan(Plan);
        }
コード例 #7
0
 public void Init(RunDelegate Delegate)
 {
     if (mainFiberHandle == IntPtr.Zero)
     {
         mainFiberHandle = ConvertThreadToFiber(0);
     }
     fiberHandle = CreateFiber(500, Delegate, 0);
 }
コード例 #8
0
 public void Init(RunDelegate Delegate)
 {
     if (mainFiberHandle == IntPtr.Zero)
     {
         mainFiberHandle = ConvertThreadToFiber(0);
     }
     fiberHandle = CreateFiber(500, Delegate, 0);
 }
コード例 #9
0
        static void Main(string[] args)
        {
            RunDelegate  r1 = new RunDelegate(Run);
            StopDelegate s1 = new StopDelegate(Stop);

            r1();
            s1();
            Console.Read();
        }
コード例 #10
0
ファイル: ProducerConsumer.cs プロジェクト: Azure/RingMaster
 public ProducerConsumer(RunDelegate run, int maxThreads, int maxQueueLength = int.MaxValue)
 {
     this.runFunction        = run;
     this.maxThreads         = maxThreads;
     this.MaxQueueLength     = maxQueueLength;
     this.queueFullSemaphore = maxQueueLength != int.MaxValue
         ? new SemaphoreSlim(maxQueueLength, maxQueueLength)
         : null;
 }
コード例 #11
0
ファイル: miniKanren.cs プロジェクト: WinMustDie/miniKanren
		public static List<List<object>> Run(int stepsCount, RunDelegate func, int argsCount)
		{
			if (stepsCount == 0)
				return new List<List<object>>();

			var args = Enumerable.Range(1, argsCount).Select(i => new LogicVar()).ToList();
			var substs = func(args)(GetEmptySubst());

			int stepNumber = 0;
			return substs.TakeWhile(subst => stepNumber++ != stepsCount)
				.Select(subst => args
					.Select(a =>
					{
						var val = subst.GetValue(a);
						return val is LogicVar ? null : val;
					}).ToList())
				.ToList();
		}
コード例 #12
0
    public void StartRemoteJob()
    {
        string error;

        _checkInputFile      = false;
        _theTabs.SelectedTab = _tabLog;
        _log.Text            = "";

        Interlocked.Increment(ref Scheduler.numNetJobsRunning);
        //_houston.SetStatusBarText(Scheduler.numJobsRunning.ToString());

        _job = null;
        _net = new SfbClient(this);
        SetSubItem(Display.cpu, "0.0s");
        SetSubItem(Display.mem, "0kb");
        if ((error = _net.Connect(remotehost, remoteport, filetype)) == null)
        {
            string requiredversion = "";

            if (filetype == FileType.sfbox && _net.ServerVersionIsAtLeast(requiredversion = "0.5") || (filetype == FileType.mcrenko || filetype == FileType.ctb) && _net.ServerVersionIsAtLeast(requiredversion = "0.7"))
            {
                this._houston.AddtoRegistry(remotehost, remoteport);

                ArrayList news = _net.GetNews();

                string shortName = _net.SendInputFile(FullName);

                if (filetype == FileType.mcrenko)
                {
                    RemoteCompileMC(_net);
                }

                SetStartTime(DateTime.Now);
                SetStatus(Status.running);

                RunDelegate   run             = new RunDelegate(RunAndDownload);
                AsyncCallback myAsyncCallback = new AsyncCallback(NetHasExited);
                run.BeginInvoke(_net, shortName, DirectoryName, this, myAsyncCallback, null);

                PopupMessages(news);
            }
            else
            {
                SetStatus(Status.aborted);
                MessageBox.Show("You need at least server version " + requiredversion + " for what you are trying to do.", "Server error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Interlocked.Decrement(ref Scheduler.numNetJobsRunning);
            }
        }
        else
        {
            SetStatus(Status.aborted);
            MessageBox.Show("Server connection error:\n\n" + error, "Server error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            _log.AppendText("\r\nCould not connect: " + error);
            Interlocked.Decrement(ref Scheduler.numNetJobsRunning);
            //_houston.SetStatusBarText(Scheduler.numJobsRunning.ToString());
        }
    }
コード例 #13
0
        public void Perform()
        {
            RunDelegate run = new RunDelegate(RunThis);

            run(1024);


            run = RunThat;
            run(1024);
        }
コード例 #14
0
 public ComponentPool(DataManager dataManager)
 {
     RunAnalysis         = new RunDelegate(Run);
     _analysisComponents = GetEnumerableOfType <AnalysisLoop>(dataManager).OrderBy(s => s.Priority);
     _sequenceLoop       = GetEnumerableOfType <SequenceLoop>(dataManager).OrderBy(s => s.Priority);
     _singleLoops        = GetEnumerableOfType <SingleLoop>(dataManager).OrderBy(s => s.Priority);
     _initialRun         = GetEnumerableOfType <InitialLoop>(dataManager).OrderBy(s => s.Priority);
     _dataManager        = dataManager;
     _dataManager.AnalysisNames.Add("Wholegenome");
 }
コード例 #15
0
        public void Test2()
        {
            RunDelegate run = new RunDelegate(RunThis);

            run(1024);

            //run = new RunDelegate(RunThat);
            // omit new RunDelegate
            run = RunThat; // no parenthesis ()
            run(1024);
        }
コード例 #16
0
ファイル: TaskFactory.cs プロジェクト: FlameFires/QCrawler
        public void Run <T>(RunDelegate <T> action, T paras)
        {
            semaphore.WaitOne();
            var t = Task.Run(() =>
            {
                action?.Invoke(paras);
                semaphore.Release();
            });

            tasks.Add(t);
        }
コード例 #17
0
ファイル: TaskFactory.cs プロジェクト: FlameFires/QCrawler
        public void Run <T1, T2, T3>(RunDelegate <T1, T2, T3> runDelegate, T1 t1, T2 t2, T3 t3)
        {
            semaphore.WaitOne();
            var t = Task.Run(() =>
            {
                runDelegate?.Invoke(t1, t2, t3);
                semaphore.Release();
            });

            tasks.Add(t);
        }
コード例 #18
0
ファイル: miniKanren.cs プロジェクト: VPetukhov/miniKanren
        public static List <List <object> > Run(int stepsCount, RunDelegate func, int argsCount)
        {
            if (stepsCount == 0)
            {
                return(new List <List <object> >());
            }

            var args   = Enumerable.Range(1, argsCount).Select(i => new LogicVar()).ToList();
            var substs = func(args)(GetEmptySubst());

            int stepNumber = 0;

            return(substs.TakeWhile(subst => stepNumber++ != stepsCount)
                   .Select(subst => args
                           .Select(a =>
            {
                var val = subst.GetValue(a);
                return val is LogicVar ? null : val;
            }).ToList())
                   .ToList());
        }
コード例 #19
0
  public static void Main(){
		RunDelegate runDelegate1 = new RunDelegate(Run);
		RunDelegate runDelegate2 = new RunDelegate(Run);
		IAsyncResult result1 = runDelegate1.BeginInvoke("Hello", null, null);
		IAsyncResult result2 = runDelegate2.BeginInvoke("World!", null, null);
		while(!(result1.IsCompleted && result2.IsCompleted)){
			Console.Write(" - ");
			Thread.Sleep(1000);
		}
		runDelegate1.EndInvoke(result1);
		runDelegate2.EndInvoke(result2);
		Console.WriteLine("\nMain thread exiting now...bye!");
  } // end Main() method
コード例 #20
0
ファイル: Program.cs プロジェクト: yangheejune/-
        public void Perform()
        {
            // 2. delegate 인스턴스 생성 Wrapper 클래스 이므로 클래스 처럼 객체를 생성해야함.
            RunDelegate run = new RunDelegate(RunThis);

            // 3. delegate 실행
            run(1024);

            // run = new RunDelegate(RunThat); 을 줄여서
            // 아래와 같이 쓸 수 있다.
            run = RunThat;

            run(1024);
        }
コード例 #21
0
        public RunDelegate Build()
        {
            RunDelegate app = () =>
            {
                return(Task.CompletedTask);
            };

            foreach (var component in _components.Reverse())
            {
                app = component(app);
            }

            return(app);
        }
コード例 #22
0
ファイル: MyClass.cs プロジェクト: lamnun/ConsoleApp6
        public void Perform()
        {
            // 2. delegate 인스턴스 생성
            RunDelegate run = new RunDelegate(RunThis);

            // 3. delegate 실행
            run(1024);

            //run = new RunDelegate(RunThat); 을 줄여서
            //아래와 같이 쓸 수 있다.
            run = RunThat;

            run(1024);
        }
コード例 #23
0
        public UserInterface(DataManager dataManager, RunDelegate run)
        {
            InitializeComponent();

            _dataManager       = dataManager;
            _runAnalysis       = run;
            _updateProgressBar = new UpdateProgressBar(updateProgressBar);

            uxRunToolbar.Enabled          = false;
            uxSequenceList.ItemCheck     += uxSequenceListItem_Click;
            uxOutputLocationTextBox.Text  = _dataManager.MainOutputFolder;
            uxVaccineLocationTextBox.Text = _dataManager.VaccineLocation;
            uxMinOrfLengthTextbox.Text    = _dataManager.MinimumOrfLength.ToString();
            uxAlignmentType.SelectedItem  = _dataManager.MafftSettings;
        }
コード例 #24
0
		public void Init(RunDelegate Delegate)
		{
			if (!mainFiberSetted)
			{
				mainFiberSetted = true;
				fixed (ucontext_t *mainFiberHandlePtr = &mainFiberHandle) 
				{
					getcontext(mainFiberHandlePtr);
				}
			}
			fixed (ucontext_t *fiberHandlePtr = &fiberHandle) 
			{
				makecontext(fiberHandlePtr, Delegate, 0);
			}
		}
コード例 #25
0
ファイル: NullPool.cs プロジェクト: NeoTim/etch
 public void Run(RunDelegate d1, ExceptionDelegate d2)
 {
     new Thread(
         new ThreadStart(delegate()
     {
         try
         {
             d1();
         }
         catch (Exception e)
         {
             d2(e);
         }
     })).Start();
 }
コード例 #26
0
 public static void Run(RunDelegate runProc = null)
 {
     if (!Initialized)
     {
         Initialize();
     }
     if (runProc != null)
     {
         runProc();
     }
     Application.Run();
     if (OnStopped != null)
     {
         OnStopped();
     }
 }
コード例 #27
0
        public void Init(RunDelegate Delegate)
        {
            if (!mainFiberSetted)
            {
                mainFiberSetted = true;
                fixed(ucontext_t *mainFiberHandlePtr = &mainFiberHandle)
                {
                    getcontext(mainFiberHandlePtr);
                }
            }

            fixed(ucontext_t *fiberHandlePtr = &fiberHandle)
            {
                makecontext(fiberHandlePtr, Delegate, 0);
            }
        }
コード例 #28
0
ファイル: Benchmark.cs プロジェクト: tmpkus/openvss
        private static void TimeAndDisplay(string name, XmlTextWriter xtw, RunDelegate init, RunDelegate run, RunDelegate flush, int count, int divider)
        {
            double min, max, avg;

            TimeAndDiscardUnusual(init, run, flush, count, 10, out min, out max, out avg);
            max /= divider;
            min /= divider;
            avg /= divider;
            Console.WriteLine("{0}: min={1}ns max={2}ns avg={3}ns", name, Math.Round(min, 3), Math.Round(max, 3), Math.Round(avg, 3));
            xtw.WriteStartElement("test");
            xtw.WriteAttributeString("name", name);
            xtw.WriteAttributeString("min", Convert.ToInt32(min).ToString());
            xtw.WriteAttributeString("max", Convert.ToInt32(max).ToString());
            xtw.WriteAttributeString("avg", Convert.ToInt32(avg).ToString());
            xtw.WriteEndElement();
            _maxmax = Math.Max(_maxmax, max);
        }
コード例 #29
0
        /// <summary>
        /// Initializes a new instance of the <see cref="WafNative"/> class.
        /// </summary>
        /// <param name="handle">Can't be a null pointer. Waf library must be loaded by now</param>
        internal WafNative(IntPtr handle)
        {
            _initField                  = GetDelegateForNativeFunction <InitDelegate>(handle, "ddwaf_init");
            _destroyField               = GetDelegateForNativeFunction <DestroyDelegate>(handle, "ddwaf_destroy");
            _initContextField           = GetDelegateForNativeFunction <InitContextDelegate>(handle, "ddwaf_context_init");
            _runField                   = GetDelegateForNativeFunction <RunDelegate>(handle, "ddwaf_run");
            _contextDestroyField        = GetDelegateForNativeFunction <ContextDestroyDelegate>(handle, "ddwaf_context_destroy");
            _resultFreeField            = GetDelegateForNativeFunction <ResultFreeDelegate>(handle, "ddwaf_result_free");
            _objectInvalidField         = GetDelegateForNativeFunction <ObjectInvalidDelegate>(handle, "ddwaf_object_invalid");
            _objectStringLengthFieldX64 =
                Environment.Is64BitProcess ?
                GetDelegateForNativeFunction <ObjectStringLengthDelegateX64>(handle, "ddwaf_object_stringl") :
                null;
            _objectStringLengthFieldX86 =
                Environment.Is64BitProcess ?
                null :
                GetDelegateForNativeFunction <ObjectStringLengthDelegateX86>(handle, "ddwaf_object_stringl");
            _objectSignedField    = GetDelegateForNativeFunction <ObjectSignedDelegate>(handle, "ddwaf_object_signed");
            _objectUnsignField    = GetDelegateForNativeFunction <ObjectUnsignedDelegate>(handle, "ddwaf_object_unsigned");
            _objectArrayField     = GetDelegateForNativeFunction <ObjectArrayDelegate>(handle, "ddwaf_object_array");
            _objectMapField       = GetDelegateForNativeFunction <ObjectMapDelegate>(handle, "ddwaf_object_map");
            _objectArrayAddField  = GetDelegateForNativeFunction <ObjectArrayAddDelegate>(handle, "ddwaf_object_array_add");
            _objectMapAddFieldX64 =
                Environment.Is64BitProcess ?
                GetDelegateForNativeFunction <ObjectMapAddDelegateX64>(handle, "ddwaf_object_map_addl") :
                null;
            _objectMapAddFieldX86 =
                Environment.Is64BitProcess ?
                null :
                GetDelegateForNativeFunction <ObjectMapAddDelegateX86>(handle, "ddwaf_object_map_addl");
            _objectFreeField = GetDelegateForNativeFunction <ObjectFreeDelegate>(handle, "ddwaf_object_free", out _objectFreeFuncPtrField);
            _getVersionField = GetDelegateForNativeFunction <GetVersionDelegate>(handle, "ddwaf_get_version");

            // setup logging
            var setupLogging = GetDelegateForNativeFunction <SetupLoggingDelegate>(handle, "ddwaf_set_log_cb");

            // convert to a delegate and attempt to pin it by assigning it to  field
            setupLogCallbackField = LoggingCallback;
            // set the log level and setup the logger
            var level = GlobalSettings.Source.DebugEnabled ? DDWAF_LOG_LEVEL.DDWAF_DEBUG : DDWAF_LOG_LEVEL.DDWAF_INFO;

            setupLogging(Marshal.GetFunctionPointerForDelegate(setupLogCallbackField), level);
        }
コード例 #30
0
        /// <summary>
        /// 以指定的时间间隔调用检测函数,若检测函数返回true,则执行运行函数,
        /// 若检测函数被调用一定次数后仍然返回false,则不执行运行函数。
        /// </summary>
        /// <param name="interval">间隔时间。每隔Interval毫秒,checkFunction就会被调用一次</param>
        /// <param name="checkFunction">检测函数。返回true代表检测成功,反之失败</param>
        /// <param name="runFunction">运行函数。</param>
        /// <param name="maxCheckCount">最大检测次数。如果超过了maxCheckCount,checkFunction仍然返回false,则runFunction不会被调用
        ///                     <para>当检测次数为0时,则为无限循环,直到checkFunction满足条件后方才退出</para></param>
        public CheckRunner(int interval, CheckDelegate checkFunction, RunDelegate runFunction, int maxCheckCount)
        {
            _attemptCount = maxCheckCount;
            if (_attemptCount == 0)
            {
                isInfiniteLoop = true;
            }
            _checkFunction = checkFunction;
            _runFunction   = runFunction;

            _timer.Elapsed += new ElapsedEventHandler(delegate(object sender, ElapsedEventArgs e)
            {
                if (_isEnter)
                {
                    return;
                }
                _isEnter = true;

                if (!isInfiniteLoop)
                {
                    _attemptCount--;
                }

                if (_checkFunction())
                {
                    if (!_isRunned)
                    {
                        _runFunction();
                        _isRunned = true;
                    }
                    _timer.Enabled = false;
                }
                else if (_attemptCount <= 0 && !isInfiniteLoop)
                {
                    _timer.Enabled = false;
                }

                _isEnter = false;
            });
            _timer.Interval = interval;
            _timer.Enabled  = true;
        }
コード例 #31
0
ファイル: Program.cs プロジェクト: Dobitk/HomeSolution
        static void Main(string[] args)
        {
            Console.WriteLine("1. Создайте тип делегата, тип возвращаемого значения которого" +
                              " будет созданный вами пользовательский класс. В созданном вами " +
                              "класса создайте метод, который будет выводить строку в консоль и " +
                              "соотвествующий тип делегата для этого метода. (Условие запутанное. Как понял так и написал.)");
            Console.WriteLine(Environment.NewLine);
            Delegate1UserModule.sdDelegate();

            Delegate2UserModule Startdelegate2 = new Delegate2UserModule();

            Startdelegate2.sdDelegate(10, 2);
            Console.WriteLine(Environment.NewLine);

//===================================================================================================================================
            Console.WriteLine("2. Обьявите обобщенный тип делегата с одним входящим " +
                              "параметром, возвращаемый тип и тип параметра должны опеределятся " +
                              "во время создания делегата разными PLACEHOLDER`ами. Задайте действия " +
                              "делегата лямбда выражением и вызовите делегат.");
            Console.WriteLine(Environment.NewLine);

            RunDelegate.RunDelegate1(25);
            RunDelegate.RunDelegate1(2545646546152659);
            RunDelegate.RunDelegate1(3.14);
            RunDelegate.RunDelegate1(true);
            RunDelegate.RunDelegate1("Строковое значение");
            Console.WriteLine(Environment.NewLine);
            //===================================================================================================================================

            Console.WriteLine("3. Создайте класс Cat и обьявите в нем событие WakeUpEvent. " +
                              "Создайте классы подписчики Dog, Mouse, Human. Подпишитесь в " +
                              "этих классах на событие WakeUpEvent и пропишите с помощью " +
                              "вывода в консоль что должны делать каждый из классов " +
                              "подписчиков когда происходит событие.");
            Console.WriteLine(Environment.NewLine);

            Dog.Dogs();
            Console.WriteLine(Environment.NewLine);
            Mouse.Mouses();
            Console.WriteLine(Environment.NewLine);
            Human.Humans();
        }
コード例 #32
0
       /// <summary>
       /// 以指定的时间间隔调用检测函数,若检测函数返回true,则执行运行函数,
       /// 若检测函数被调用一定次数后仍然返回false,则不执行运行函数。
       /// </summary>
       /// <param name="interval">间隔时间。每隔Interval毫秒,checkFunction就会被调用一次</param>
       /// <param name="checkFunction">检测函数。返回true代表检测成功,反之失败</param>
       /// <param name="runFunction">运行函数。</param>
       /// <param name="maxCheckCount">最大检测次数。如果超过了maxCheckCount,checkFunction仍然返回false,则runFunction不会被调用
       ///                     <para>当检测次数为0时,则为无限循环,直到checkFunction满足条件后方才退出</para></param>
       public CheckRunner(int interval, CheckDelegate checkFunction, RunDelegate runFunction, int maxCheckCount)
       {
           _attemptCount = maxCheckCount;
           if (_attemptCount == 0)
           {
               isInfiniteLoop = true;
           }
           _checkFunction = checkFunction;
           _runFunction = runFunction;

           _timer.Elapsed += new ElapsedEventHandler(delegate(object sender, ElapsedEventArgs e)
           {
               if (_isEnter)
               {
                   return;
               }
               _isEnter = true;

               if (!isInfiniteLoop)
               {
                   _attemptCount--;
               }

               if (_checkFunction())
               {
                   if (!_isRunned)
                   {
                       _runFunction();
                       _isRunned = true;
                   }
                   _timer.Enabled = false;
               }
               else if (_attemptCount <= 0 && !isInfiniteLoop)
               {
                   _timer.Enabled = false;
               }

               _isEnter = false;
           });
           _timer.Interval = interval;
           _timer.Enabled = true;
       }
コード例 #33
0
        public void Run()
        {
            if (Plan.PositionLogs == null || Plan.PositionLogs.Count == 0)
            {
                _log.LogError(Plan.Id, "There are no positions to execute the forecast");
                throw new ForecastServiceException("There are no positions to execute the forecast");
            }
            if (Plan.GetStatus() == ForecastPlanStatus.Running)
            {
                _log.LogWarning(Plan.Id, "Already Running");
                throw new ForecastServiceException("Already Running");
            }
            _dataService.DeleteResults(Plan.Id);
            Plan.SetStatus(ForecastPlanStatus.Running);
            _dataService.UpdateForecastPlan(Plan);
            //_dataService.DeleteResults(Plan.Id);
            var runDelegate = new RunDelegate(ExecutePositions);

            runDelegate.BeginInvoke(RunCallback, runDelegate);
        }
コード例 #34
0
        public static void Main()
        {
            ExamplesOnDelegate obj  = new ExamplesOnDelegate();
            RunDelegate        obj1 = () => {
                Console.WriteLine("Using Lamda Exprssion calls");
            };

            obj1 += obj.RunFast; obj1 += obj.Run;
            obj1.Invoke();

            RunSlowDelegate obj2 = (string s) =>
            {
                Console.WriteLine("Lamda Expression");
            };

            obj2.Invoke("helo");

            Console.WriteLine("Example Completed");
            Console.ReadKey();
        }
コード例 #35
0
        public WaveformUserControl()
        {
            InitializeComponent();
            core            = new WaveformCore(this);
            dragDropManager = new ListViewDragDropManager(core, ListViewMain);
            dragDropManager.UpdateViewEvent += new UpdateView(dragDropManager_UpdateViewEvent);
            core.ScaleManager            = new ScaleManager(core, timeScaleViewer);
            timeScaleViewer.ScaleManager = core.ScaleManager;
            timeScaleViewer.ScaleManager.PropertyChanged += new PropertyChangedEventHandler(ScaleManager_PropertyChanged);
            cursorViewer = new CursorViewer(this, core);
            cursorViewer.CursorPositionChangedEvent += new UpdateView(cursorViewer_CursorPositionChangedEvent);
            TreeListView.AllowMultiSelection(ListViewMain);
            core.CursorViewer         = cursorViewer;
            actionMode                = WaveformActionMode.Cursor;
            TimeMeasureDataView1.Core = core;
            lines = new List <Line>();;
            core.TimeMeasureList.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(TimeMeasureList_CollectionChanged);

            runEvent = new RunDelegate(CustomRunCommandHandler);
        }
コード例 #36
0
ファイル: Benchmark.cs プロジェクト: tdhieu/openvss
        private static double TimeCode(RunDelegate init, RunDelegate run, RunDelegate flush, int count)
        {
            int unrollCount = 10;
            if (init != null)
                init();
            run();
            run();
            run();
            StopWatch sw = new StopWatch();
            sw.Start();

            for (int i = 0; i < count; ++i)
            {
                run();
                run();
                run();
                run();
                run();
                run();
                run();
                run();
                run();
                run();
            }
            if (flush != null)
                flush();
            sw.Stop();
            return sw.Nanoseconds / (count * unrollCount);
        }
コード例 #37
0
ファイル: Benchmark.cs プロジェクト: tdhieu/openvss
        private static void TimeAndDisplay(string name, XmlTextWriter xtw, RunDelegate init, RunDelegate run, RunDelegate flush, int count, int divider)
        {
            double min, max, avg;

            TimeAndDiscardUnusual(init, run, flush, count, 10, out min, out max, out avg);
            max /= divider;
            min /= divider;
            avg /= divider;
            Console.WriteLine("{0}: min={1}ns max={2}ns avg={3}ns", name, Math.Round(min, 3), Math.Round(max, 3), Math.Round(avg, 3));
            xtw.WriteStartElement("test");
            xtw.WriteAttributeString("name", name);
            xtw.WriteAttributeString("min", Convert.ToInt32(min).ToString());
            xtw.WriteAttributeString("max", Convert.ToInt32(max).ToString());
            xtw.WriteAttributeString("avg", Convert.ToInt32(avg).ToString());
            xtw.WriteEndElement();
            _maxmax = Math.Max(_maxmax, max);
        }
コード例 #38
0
ファイル: Direct.cs プロジェクト: Radulfr/zeroc-ice
        public Direct(Ice.Current current, RunDelegate run)
        {
            _current = current;
            _run = run;
            
            Ice.ObjectAdapterI adapter = (Ice.ObjectAdapterI)_current.adapter;
            Debug.Assert(adapter != null);
            
            //
            // Must call incDirectCount() first, because it checks for
            // adapter deactivation, and prevents deactivation completion
            // until decDirectCount() is called. This is important,
            // because getServantManager() may not be called afer
            // deactivation completion.
            //
            adapter.incDirectCount();
            
            ServantManager servantManager = adapter.getServantManager();
            Debug.Assert(servantManager != null);
            
            _servant = servantManager.findServant(_current.id, _current.facet);
            if(_servant == null)
            {
                _locator = servantManager.findServantLocator(_current.id.category);
                if(_locator == null && _current.id.category.Length > 0)
                {
                    _locator = servantManager.findServantLocator("");
                }
                if(_locator != null)
                {
                    try
                    {
                        _servant = _locator.locate(_current, out _cookie);
                    }
                    catch(System.Exception)
                    {
                        adapter.decDirectCount();
                        throw;
                    }
                }
            }

            if(_servant == null)
            {
                adapter.decDirectCount();
                if(servantManager != null && servantManager.hasServant(_current.id))
                {
                    Ice.FacetNotExistException ex = new Ice.FacetNotExistException();
                    ex.id = _current.id;
                    ex.facet = _current.facet;
                    ex.operation = _current.operation;
                    throw ex;
                }
                else
                {
                    Ice.ObjectNotExistException ex = new Ice.ObjectNotExistException();
                    ex.id = _current.id;
                    ex.facet = _current.facet;
                    ex.operation = _current.operation;
                    throw ex;
                }
            }
        }
コード例 #39
0
		//extern void makecontext(IntPtr* __ucp, RunDelegate __func, int __argc, params IntPtr __rest);
		static extern void makecontext(ucontext_t* __ucp, RunDelegate __func, int __argc);
コード例 #40
0
ファイル: Benchmark.cs プロジェクト: tdhieu/openvss
        private static void TimeAndDiscardUnusual(RunDelegate init, RunDelegate run, RunDelegate flush, int count, int samples, out double min, out double max, out double avg)
        {
            double[] times = new double[samples];

            for (int i = 0; i < times.Length; ++i)
            {
                times[i] = TimeCode(init, run, flush, count) - _overhead;
            }

            Array.Sort(times);

            // discard lowest 20% and highest 20%

            int startAt = times.Length * 20 / 100;
            int endAt = times.Length * 80 / 100;

            max = times[startAt];
            min = times[startAt];
            avg = 0.0;
            int cnt = 0;

            for (int i = startAt; i < endAt; ++i)
            {
                max = Math.Max(max, times[i]);
                min = Math.Min(min, times[i]);
                avg += times[i];
                cnt++;
            }

            avg /= cnt;
        }
コード例 #41
0
ファイル: TestGame.cs プロジェクト: sergios1234/monoxna
 public DelegateBasedEventSource(RunDelegate<DelegateBasedEventSource> run)
 {
     _run = run;
 }
コード例 #42
0
ファイル: test-anon-168.cs プロジェクト: nobled/mono
	public void Run (RunDelegate test)
	{
		test (0);
	}
コード例 #43
0
ファイル: Loader.cs プロジェクト: bodji/freeswitch
 static extern void InitManagedDelegates(RunDelegate run, ExecuteDelegate execute, ExecuteBackgroundDelegate executeBackground, ReloadDelegate reload, ListDelegate list);