Beispiel #1
0
        /// <summary>
        /// 开始监听
        /// </summary>
        public void Start()
        {
            if (Running)
            {
                Log.Error(">正在监听中,重复的开始请求");
                return;
            }
            Log.Info(">开始监听");
#if NETDNX
            AppDomain.CurrentDomain.ProcessExit -= CurrentDomain_ProcessExit;
            AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;
#else
            AppDomain.CurrentDomain.DomainUnload -= CurrentDomain_DomainUnload;
            AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload;
#endif

            Starting?.Invoke(this, EventArgs.Empty);
            if (Start_IPv4())
            {
                System.Threading.Interlocked.CompareExchange(ref _running_v4, 1, 0);
            }
            if (Start_IPv6())
            {
                System.Threading.Interlocked.CompareExchange(ref _running_v6, 1, 0);
            }
            Log.Info(">监听完成");
            Started?.Invoke(this, EventArgs.Empty);
            if (Running)
            {
                StartAccept();
                _beginTime = System.DateTime.Now;
            }
        }
Beispiel #2
0
        public async Task <IImageSourceServiceResult> LoadDrawableAsync(IImageSource imageSource, Android.Widget.ImageView imageView, CancellationToken cancellationToken = default)
        {
            if (imageSource is not ICountedImageSourceStub imageSourceStub)
            {
                return(null);
            }

            try
            {
                Starting.Set();

                // simulate actual work
                var drawable = await Task.Run(() =>
                {
                    if (imageSourceStub.Wait)
                    {
                        DoWork.WaitOne();
                    }

                    var color = imageSourceStub.Color.ToPlatform();

                    return(new ColorDrawable(color));
                }).ConfigureAwait(false);

                cancellationToken.ThrowIfCancellationRequested();
                imageView.SetImageDrawable(drawable);

                return(new ImageSourceServiceLoadResult(drawable.Dispose));
            }
            finally
            {
                Finishing.Set();
            }
        }
Beispiel #3
0
 public void PlayerLoop()
 {
     Starting?.Invoke();
     event_idx       = 0;
     play_delta_time = 0;
     while (true)
     {
         pause_handle.WaitOne();
         if (do_stop)
         {
             break;
         }
         if (do_pause)
         {
             pause_handle.Reset();
             do_pause = false;
             state    = PlayerState.Paused;
             continue;
         }
         if (event_idx == messages.Count)
         {
             break;
         }
         ProcessMessage(messages [event_idx++]);
     }
     do_stop = false;
     Mute();
     state = PlayerState.Stopped;
     if (event_idx == messages.Count)
     {
         PlaybackCompletedToEnd?.Invoke();
     }
     Finished?.Invoke();
 }
Beispiel #4
0
        public async Task <IImageSourceServiceResult <Drawable> > GetDrawableAsync(ICountedImageSourceStub imageSource, Context context, CancellationToken cancellationToken = default)
        {
            try
            {
                Starting.Set();

                // simulate actual work
                var drawable = await Task.Run(() =>
                {
                    if (imageSource.Wait)
                    {
                        DoWork.WaitOne();
                    }

                    var color = imageSource.Color.ToPlatform();

                    return(new ColorDrawable(color));
                }).ConfigureAwait(false);

                return(new Result(drawable, imageSource.IsResolutionDependent));
            }
            finally
            {
                Finishing.Set();
            }
        }
Beispiel #5
0
        public async Task <IImageSourceServiceResult <UIImage> > GetImageAsync(ICountedImageSourceStub imageSource, float scale = 1, CancellationToken cancellationToken = default)
        {
            try
            {
                Starting.Set();

                // simulate actual work
                var image = await Task.Run(() =>
                {
                    if (imageSource.Wait)
                    {
                        DoWork.WaitOne();
                    }

                    var color = imageSource.Color.ToNative();

                    return(CreateImage(scale, color));
                }).ConfigureAwait(false);

                return(new Result(image, imageSource.IsResolutionDependent));
            }
            finally
            {
                Finishing.Set();
            }
        }
Beispiel #6
0
        public async Task Run()
        {
            if (_running)
            {
                throw new InvalidOperationException();
            }

            _running = true;
            IGameState state = new Starting();

            try {
                while (state != null)
                {
                    if (_stopRequested)
                    {
                        _stopRequested = false;
                        throw new TaskCanceledException();
                    }

                    state = await state.Run(this);
                }
            } finally {
                _running = false;
            }
        }
Beispiel #7
0
        public void StartRandomTimer()
        {
            if (IsRunning)
            {
                Log.Debug($"Timer already running");
                return;
            }
            Log.Debug($"Random start triggered at {DateTime.Now}");
            IsRunning = true;

            var minimum = _propertyService.MinimumDelay;
            var window  = minimum + _propertyService.StartWindow;

            Starting?.Invoke(this, EventArgs.Empty);

            var sleep = _random.Next(minimum, window);

            Log.Information($"Sleeping for {sleep}ms");

            var timer = new CountDownTimer(TimeSpan.FromMilliseconds(sleep));

            timer.ReachedZero += (_, __) =>
            {
                Log.Information($"Start!");
                Started?.Invoke(this, EventArgs.Empty);
                IsRunning = false;
            };
            timer.Start();
        }
Beispiel #8
0
 //[XmlInclude(typeof(BuildFarmCapability)), XmlInclude(typeof(BuildBarrackCapability)), XmlInclude(typeof(BuildBowWorkshopCapability)), XmlInclude(typeof(BuildTowerCapability)), XmlInclude(typeof(BuildPeasantCapability)), XmlInclude(typeof(BuildArcherCapability))]
 public static void Main(string[] args)
 {
     var buildingTypes = new string[5] {"Farm", "Barrack","BowWorkshop","Tower","Blacksmith" };
     var unitTypes = new string[4] { "Peasant", "Archer", "Clubman", "SwordFighter" };
     UIBLC uW = new UIBLC();
     uW.BuildingTypes = buildingTypes;
     uW.UnitTypes = unitTypes;
     Serialize(uW);
     Starting s = new Starting();
     s.Resources = 200;
     Serialize(s);
     NewOptions options = new NewOptions();
     options.FarmBuildings = new string[1] { "Barrack" };
     options.FarmUnits = new string[1] { "Peasant" };
     options.BarrackBuildings = new string[1] { "BowWorkshop" };
     //options.BarrackUnits = new string[1] { "Clubman" };
     options.BowWorkshopBuildings = new string[1] { "Tower" };
     options.BowWorkshopUnits = new string[1] { "Archer" };
     //options.TowerBuildings = new string[1] { "Blacksmith" };
     //options.BlacksmithUnits = new string[1] { "SwordFighter" };
     Serialize(options);
     //var map = new Map();
     //map = map.Run(16, 16);
     //SerialMap(map);
 }
Beispiel #9
0
 private void MaybeStarted()
 {
     if (Interlocked.Exchange(ref _started, 1) == 0)
     {
         Starting?.Invoke(this, new EventArgs());
     }
 }
Beispiel #10
0
        private void StartSimulationOnConnectedPeers()
        {
            var writer = new Serializer();

            //Create a new seed and send it with a start-message to all clients
            //The message also contains the respective player-id and the initial simulation speed
            var seed = new Random().Next(int.MinValue, int.MaxValue);


            Starting?.Invoke(this, new StartedEventArgs(SimulationSpeed, _actorIds.Values.ToArray()));
            foreach (var player in _actorIds)
            {
                writer.Reset();
                writer.Put((byte)MessageTag.Init);
                new Init
                {
                    Seed            = seed,
                    ActorID         = player.Value,
                    AllActors       = _actorIds.Values.ToArray(),
                    SimulationSpeed = SimulationSpeed
                }.Serialize(writer);

                _server.Send(player.Key, Compressor.Compress(writer));
            }

            Started?.Invoke(this, new StartedEventArgs(SimulationSpeed, _actorIds.Values.ToArray()));
        }
        private static void OnStarting(string[] args)
        {
            Starting?.Invoke(null, EventArgs.Empty);

            //激发当前上下文的“Starting”事件
            _context.RaiseStarting(args);
        }
        public void Clean()
        {
            if (baseDirectory == null)
            {
                throw new ArgumentException("A directory have to be selected");
            }

            try
            {
                Starting?.Invoke(this, EventArgs.Empty);

                var taskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
                Task.Factory.StartNew(() => ParseDirectory(baseDirectory),
                                      CancellationToken.None,
                                      TaskCreationOptions.None,
                                      taskScheduler).ContinueWith((t) =>
                {
                    Completed?.Invoke(this, EventArgs.Empty);
                }, taskScheduler);
            }
            catch (Exception ex)
            {
                Failed?.Invoke(this, ex);
            }
        }
        void Model_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "TraceStates")
            {
                switch (Model.TraceStates)
                {
                case TraceStates.Running:
                    Running.Begin(cTraceState, true);
                    Starting.Stop(cTraceState);
                    Stopping.Stop(cTraceState);

                    break;

                case TraceStates.Starting:
                    Starting.Begin(cTraceState, true);
                    Stopping.Stop(cTraceState);
                    Running.Stop(cTraceState);

                    break;

                case TraceStates.Stopping:
                    Stopping.Begin(cTraceState, true);
                    Running.Stop(cTraceState);
                    Starting.Stop(cTraceState);
                    break;

                case TraceStates.Stopped:
                default:
                    Starting.Stop(cTraceState);
                    Stopping.Stop(cTraceState);
                    Running.Stop(cTraceState);
                    break;
                }
            }
        }
Beispiel #14
0
 protected virtual void OnStarting(Hero playerOne, Hero playerTwo)
 {
     Starting?.Invoke(this, new StartEventArgs()
     {
         PlayerOne = playerOne,
         PlayerTwo = playerTwo
     });
 }
Beispiel #15
0
 private void OnStarting(Object sender, EventArgs e)
 {
     _publishers.TryAddSubscriber(this);
     Starting?.Invoke(this, e);
     foreach (var series in _seriesProcessors)
     {
         series.IsStarted = true;
     }
 }
Beispiel #16
0
        private void OnStarting()
        {
            Starting?.Invoke(this, EventArgs.Empty);

            _icon.Show();
            _process.Start();
            _process.BeginOutputReadLine();
            _process.BeginErrorReadLine();
            Application.Run();
        }
Beispiel #17
0
 public Game(string gameOwner, int length = 24)
 {
     this.Starting     = DateTime.Now;
     this.Ending       = Starting.AddHours(length);
     this.GameId       = Guid.NewGuid();
     this._guessNumber = _generator.Next(1, 100);
     this.Players      = new List <string>();
     this.Players.Add(gameOwner);
     Game._activeGames.Add(this);
 }
Beispiel #18
0
        public void Start()
        {
            if (Started)
            {
                Stop();
            }

            Starting?.Invoke();

            thread.Start();
        }
Beispiel #19
0
        /// <summary>
        /// 引发异步的 <see cref="Starting"/> 事件,并在事件的执行异步结束之后继续执行命令的其他部分。
        /// </summary>
        protected override async Task <CommandStartingEventArgs> OnStarting()
        {
            var startingArgs = new CommandStartingEventArgs();

            if (Starting != null)
            {
                await Starting.Invoke(this, startingArgs).ConfigureAwait(false);
            }

            return(startingArgs);
        }
Beispiel #20
0
    // FIXME this needs some work, to be completely in-tune with needs.
    public void MediaEventLoop(Action <double> UpdateProgress)
    {
        mediaEvent.CancelDefaultHandling(EventCode.StateChange);
        //mediaEvent.CancelDefaultHandling(EventCode.Starvation);
        while (stopMediaEventLoop == false)
        {
            try
            {
                EventCode ev;
                IntPtr    p1, p2;
                if (mediaEvent.GetEvent(out ev, out p1, out p2, 0) == 0)
                {
                    switch (ev)
                    {
                    case EventCode.Complete:
                        Stopping.Fire(this, null);
                        if (UpdateProgress != null)
                        {
                            UpdateProgress(source.PercentageCompleted);
                        }
                        return;

                    case EventCode.StateChange:
                        FilterState state = (FilterState)p1.ToInt32();
                        if (state == FilterState.Stopped || state == FilterState.Paused)
                        {
                            Stopping.Fire(this, null);
                        }
                        else if (state == FilterState.Running)
                        {
                            Starting.Fire(this, null);
                        }
                        break;
                        // FIXME add abort and stuff, and propagate this.
                    }
                    //                        Trace.WriteLine(ev.ToString() + " " + p1.ToInt32());
                    mediaEvent.FreeEventParams(ev, p1, p2);
                }
                else
                {
                    if (UpdateProgress != null)
                    {
                        UpdateProgress(source.PercentageCompleted);
                    }
                    // FiXME use AutoResetEvent
                    Thread.Sleep(100);
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine("MediaEventLoop: " + e);
            }
        }
    }
Beispiel #21
0
 private void OnStarting()
 {
     try
     {
         Starting?.Invoke();
     }
     catch (Exception e)
     {
         _logger.Error("Starting event handler error", e);
     }
 }
Beispiel #22
0
        public void Start()
        {
            transitioning = true;

            //start all processes
            foreach (var process in processes)
            {
                process.Start();
            }

            Starting?.Invoke(this, EventArgs.Empty);
        }
Beispiel #23
0
        public void Start()
        {
            //Clean up
            activeStates.Clear();

            //Set up
            activeStates.AddLast(startState);
            startState.Activate();

            //invoke the OnStart event which allows the user to add more functionality to the Start method
            Starting?.Invoke(this, EventArgs.Empty);
        }
Beispiel #24
0
        /// <summary>
        /// Start the background processing task, there may only be one running at a time.
        /// </summary>
        /// <exception cref="InvalidOperationException">Thrown if the task is running already.</exception>
        public void StartBackgroundTask()
        {
            if (!backgroundTask.IsCompleted)
            {
                throw new InvalidOperationException("The upload task is running already");
            }

            taskCancellation = new CancellationTokenSource();
            backgroundTask   = ProcessQueue(taskCancellation.Token);
            Starting?.Invoke(this, EventArgs.Empty);
            backgroundTask.ContinueWith(HandleStoppingBackgroundTask);
        }
Beispiel #25
0
        public App()
        {
            InitializeComponent();

            DependencyRegistry.Init();

            //var vRealmDb = Realm.GetInstance();

            MainPage = new Starting();

            var embeddedResources = new ReflectionHelper().ListAllEmbeddedResources();
        }
Beispiel #26
0
        /// <summary>
        /// Starts updates on the dedicated thread.
        /// </summary>
        public void Start()
        {
            IsUpdating = true;

            Starting?.Invoke(this, EventArgs.Empty);

            shouldUpdate.Set();

            if (!updateThread.IsAlive)
            {
                updateThread.Start();
            }
        }
Beispiel #27
0
        public void Start()
        {
            Starting?.Invoke(this, EventArgs.Empty);

            while (!IsHalted)
            {
                var result = Step();
                if (result == ExecuteAction.Break)
                {
                    Breaking?.Invoke(this, EventArgs.Empty);
                    break;
                }
            }
        }
Beispiel #28
0
        public virtual void Start()
        {
            if (isAlive)
            {
                return;
            }

            UpdateDriver.Add(this);
            isAlive = true;

            Starting?.Invoke();
            StartingOneShot?.Invoke();
            StartingOneShot = null;
        }
Beispiel #29
0
        public static void LegitInitialize(EntityBase *EntityBase, TeamID EntityTeam, TeamID PlayerBaseTeam)
        {
            ActiveWeapon = ConfigManager.CAimWeapon[Starting.GetWeaponID(BaseWeapon.ActiveWeaponIndex)];

            if (NativeMethods.GetAsyncKeyState(KeysCode.MS_Click1))
            {
                if (ActiveWeapon.WeaponActive && BaseWeapon.ActiveWeaponClip > 0)
                {
                    if (!IsClosed)
                    {
                        entity   = GetTarget(EntityBase, ActiveWeapon, EntityTeam, PlayerBaseTeam);
                        IsClosed = true;
                    }

                    if (entity != null && entity->Health > 0)
                    {
                        if (ActiveWeapon.SilentActive && BasePlayer.Bullet(false))
                        {
                            SetViewAngelSilent(AngelToTarget(entity, ActiveWeapon.WeaponBone, ActiveWeapon.RcsValue, ActiveWeapon.RcsActive));
                        }
                        else
                        {
                            VEngineClient.ViewAngels = Vector.SmoothAngle(VEngineClient.ViewAngels, AngelToTarget(entity, ActiveWeapon.WeaponBone, ActiveWeapon.RcsValue, ActiveWeapon.RcsActive), ActiveWeapon.Smooth);
                        }
                    }
                    else
                    {
                        IsClosed = false;
                    }

                    if (ActiveWeapon.RcsStandaloneActive && BasePlayer.Bullet(true))
                    {
                        RcsStandalone(ActiveWeapon.RcsStandaloneX, ActiveWeapon.RcsStandaloneY);
                    }
                }

                if (ConfigManager.CAimMisc.MouseAttackActive)
                {
                    VClient.ForceAttack = VClient.SUserCMD.ButtonID.IN_ATTACK;
                }
            }
            else
            {
                OldAngle.X = OldAngle.Y = 0.0f;
                IsClosed   = false;

                VClient.ForceAttack = VClient.SUserCMD.ButtonID.IN_NOATTACK;
            }
        }
Beispiel #30
0
        public CoreCoordinator(ITypeFinder typeFinder,
                               IPublisherProvider publishers, IWorkerContainer workers)
        {
            _typeFinder = typeFinder;

            _publishers                  = publishers;
            _publishers.Starting        += (sender, e) => Starting?.Invoke(sender, e);
            _publishers.Finishing       += (sender, e) => Finishing?.Invoke(sender, e);
            _publishers.Finished        += (sender, e) => Finished?.Invoke(sender, e);
            _publishers.ProgressChanged += (sender, e) => ProgressChanged?.Invoke(sender, e);
            _publishers.PublisherAdded  += (o, e) => PublisherAdded?.Invoke(o, e);
            _publishers.Cancelling      += (o, e) => Cancelling?.Invoke(o, e);

            _workers = workers;
        }
        ///
        public void Initialize()
        {
            Starting?.Invoke(this, Initializables.Count());

            //sort components to have an order
            var normalCmps = Initializables.Where(c => !(c is IPriorizedInitialize)).ToList();
            var prioCmps   = Initializables.Except(normalCmps).OrderBy(c => ((IPriorizedInitialize)c).RunLevel);

            var sortedComponents = new List <IInitializable>();

            sortedComponents.AddRange(prioCmps);
            sortedComponents.AddRange(normalCmps);

            ThreadPool.QueueUserWorkItem(state => InitializeComponents(sortedComponents));
        }
Beispiel #32
0
 public static void Serialize(Starting s)
 {
     XmlSerializer serializer = new XmlSerializer(typeof(Starting));
     // WARNING !!! You might need to change this link in order to make this project work
     using (TextWriter writer = new StreamWriter(@"C:/Users/Andrei/Source/Repos/uWarcraft/Uwarcraft/Serialization/starting.xml"))
     {
         serializer.Serialize(writer, s);
     }
 }