public Server(IPlayerManager playerManager, ISpectatorManager spectatorManager, IPieceProvider pieceProvider, IActionQueue gameActionQueue) { if (playerManager == null) { throw new ArgumentNullException(nameof(playerManager)); } Options = new GameOptions(); Options.ResetToDefault(); _pieceProvider = pieceProvider; _pieceProvider.Occurancies = () => Options.PieceOccurancies; _playerManager = playerManager; _spectatorManager = spectatorManager; _gameActionQueue = gameActionQueue; _hosts = new List <IHost>(); Assembly entryAssembly = Assembly.GetEntryAssembly(); if (entryAssembly != null) { Version version = entryAssembly.GetName().Version; Version = new Versioning { Major = version.Major, Minor = version.Minor, }; }// else, we suppose SetVersion will be called later, before connecting _gameStatistics = new Dictionary <string, GameStatisticsByPlayer>(); _winList = new List <WinEntry>(); State = ServerStates.WaitingStartServer; }
/// <summary> /// Calls a function on a message queue and returns a task to await the response. /// </summary> /// <typeparam name="T">Type of response.</typeparam> /// <param name="actionQueue">The message queue thread.</param> /// <param name="func">The function.</param> /// <returns>A task to await the result.</returns> public static Task <T> RunAsync <T>(this IActionQueue actionQueue, Func <T> func) { var taskCompletionSource = new TaskCompletionSource <T>(); actionQueue.Dispatch(() => { try { var result = func(); // TaskCompletionSource<T>.SetResult can call continuations // on the awaiter of the task completion source. We want to // prevent the action queue thread from executing these // continuations. Task.Run(() => taskCompletionSource.SetResult(result)); } catch (Exception ex) { // TaskCompletionSource<T>.SetException can call continuations // on the awaiter of the task completion source. We want to // prevent the action queue thread from executing these // continuations. Task.Run(() => taskCompletionSource.SetException(ex)); } }); return(taskCompletionSource.Task); }
public void MultipleThreads() { ManualDispatcher dispatcher = new ManualDispatcher(); IActionQueue queue = dispatcher.CreateQueue(); Thread thread1 = new Thread(new ThreadStart(() => { ThreadWorkerA(queue); })); Thread thread2 = new Thread(new ThreadStart(() => { ThreadWorkerB(queue); })); // start the threads counter = 0; thread1.Start(); thread2.Start(); // spin waiting for threads to end while (thread1.IsAlive || thread2.IsAlive) { dispatcher.ProcessQueues(); } dispatcher.ProcessQueues(); Assert.IsTrue(counter == 30); }
public async Task ActionQueue_Dispose_Idempotent() { var onError = new Action <Exception>(ex => Assert.Fail()); var uiThread = await CallOnDispatcherAsync(() => new DispatcherActionQueue(onError)); var layoutThread = await CallOnDispatcherAsync(() => new LayoutActionQueue(onError)); var backgroundThread = new ActionQueue(onError, NewThreadScheduler.Default); var taskPoolThread = new ActionQueue(onError); var limitedConcurrencyThread = new LimitedConcurrencyActionQueue(onError); var queueThreads = new IActionQueue[] { uiThread, layoutThread, backgroundThread, taskPoolThread, limitedConcurrencyThread }; using (new CompositeDisposable(queueThreads)) { var waitHandle = new AutoResetEvent(false); foreach (var queueThread in queueThreads) { queueThread.Dispose(); queueThread.Dispose(); queueThread.Dispatch(() => waitHandle.Set()); Assert.IsFalse(waitHandle.WaitOne(100)); } } }
private ToolOutcome Apply(IActionQueue actionQueue, IToolBehavior toolBehavior, IToolBrush toolBrush, IEnumerable <Vector> inputPositions) { IEnumerable <Vector> toolPositions = toolBrush.ComputePositions(inputPositions); var action = toolBehavior.CreateActions(toolPositions); void ValidatedAction(World gs) { if (Validate(gs, toolBehavior, toolPositions)) { action(gs); } else { throw new InvalidOperationException("Action is not valid"); } } // TODO: don't use exception to control the flow. Need google for this. try { actionQueue.ExecuteSynchronously(ValidatedAction); return(ToolOutcome.Success); } catch (InvalidOperationException) { return(ToolOutcome.Failure); } }
public GameState(IActionQueue actionQueue) { Battlefield = new Battlefield(); Graveyard = new Graveyard(); ActionQueue = actionQueue ?? throw new ArgumentException("Please provide a valid action queue"); }
public async Task ActionQueue_RunAsync_Throws() { var onError = new Action <Exception>(ex => Assert.Fail()); var uiThread = await CallOnDispatcherAsync(() => new DispatcherActionQueue(onError)); var layoutThread = await CallOnDispatcherAsync(() => new LayoutActionQueue(onError)); var backgroundThread = new ActionQueue(onError, NewThreadScheduler.Default); var taskPoolThread = new ActionQueue(onError); var limitedConcurrencyThread = new LimitedConcurrencyActionQueue(onError); var queueThreads = new IActionQueue[] { uiThread, layoutThread, backgroundThread, taskPoolThread, limitedConcurrencyThread }; using (new CompositeDisposable(queueThreads)) { foreach (var queue in queueThreads) { var exception = new InvalidOperationException(); await AssertEx.ThrowsAsync <InvalidOperationException>( () => queue.RunAsync(() => throw exception), ex => Assert.AreSame(exception, ex)); } } }
/// <summary> /// Asserts <see cref="IActionQueue.IsOnThread"/>, throwing if the <b>false</b>. /// </summary> /// <param name="actionQueue">The message queue thread.</param> /// <exception cref="InvalidOperationException"> /// Thrown if the assertion fails. /// </exception> public static void AssertOnThread(this IActionQueue actionQueue) { if (!actionQueue.IsOnThread()) { throw new InvalidOperationException("Thread access assertion failed."); } }
/// <summary> /// Instantiates a <see cref="UIManagerModule"/>. /// </summary> /// <param name="reactContext">The React context.</param> /// <param name="viewManagers">The view managers.</param> /// <param name="uiImplementationProvider">The UI implementation provider.</param> /// <param name="layoutActionQueue">The layout action queue.</param> /// <param name="options">Options for the <see cref="UIManagerModule"/>.</param> public UIManagerModule( ReactContext reactContext, IReadOnlyList <IViewManager> viewManagers, UIImplementationProvider uiImplementationProvider, IActionQueue layoutActionQueue, UIManagerModuleOptions options) : base(reactContext, layoutActionQueue) { if (viewManagers == null) { throw new ArgumentNullException(nameof(viewManagers)); } if (uiImplementationProvider == null) { throw new ArgumentNullException(nameof(uiImplementationProvider)); } if (layoutActionQueue == null) { throw new ArgumentNullException(nameof(layoutActionQueue)); } _eventDispatcher = new EventDispatcher(reactContext); _uiImplementation = uiImplementationProvider.Create(reactContext, viewManagers, _eventDispatcher); var lazyViewManagersEnabled = IsLazyViewManagersEnabled(options); _customDirectEvents = lazyViewManagersEnabled ? GetDirectEventTypeConstants() : new JObject(); _moduleConstants = CreateConstants(viewManagers, null, _customDirectEvents, IsLazyViewManagersEnabled(options)); _layoutActionQueue = layoutActionQueue; reactContext.AddLifecycleEventListener(this); }
/// <summary> /// Instantiates a <see cref="UIManagerModule"/>. /// </summary> /// <param name="reactContext">The React context.</param> /// <param name="viewManagers">The view managers.</param> /// <param name="uiImplementationProvider">The UI implementation provider.</param> /// <param name="layoutActionQueue">The layout action queue.</param> public UIManagerModule( ReactContext reactContext, IReadOnlyList <IViewManager> viewManagers, UIImplementationProvider uiImplementationProvider, IActionQueue layoutActionQueue) : base(reactContext, layoutActionQueue) { if (viewManagers == null) { throw new ArgumentNullException(nameof(viewManagers)); } if (uiImplementationProvider == null) { throw new ArgumentNullException(nameof(uiImplementationProvider)); } if (layoutActionQueue == null) { throw new ArgumentNullException(nameof(layoutActionQueue)); } _eventDispatcher = new EventDispatcher(reactContext); _uiImplementation = uiImplementationProvider.Create(reactContext, viewManagers, _eventDispatcher); _moduleConstants = CreateConstants(viewManagers); _layoutActionQueue = layoutActionQueue; reactContext.AddLifecycleEventListener(this); }
public static async Task Initialize(IJavaScriptExecutor executor, IActionQueue jsQueueThread, string scriptPath) { #if WINDOWS_UWP var storageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx://" + "/" + scriptPath)); var filePath = storageFile.Path; #else var assembly = Assembly.GetAssembly(typeof(JavaScriptHelpers)); var assemblyName = assembly.GetName(); var pathToAssembly = Path.GetDirectoryName(assemblyName.CodeBase); if (pathToAssembly == null) { throw new FileNotFoundException($"Could not get directory name for code base of '{assemblyName}'."); } var pathToAssemblyResource = Path.Combine(pathToAssembly, scriptPath); var u = new Uri(pathToAssemblyResource); var filePath = u.LocalPath; #endif await jsQueueThread.RunAsync(() => { executor.RunScript(filePath, filePath); }); }
public Game(IActionQueue actionQueue, IPieceProvider pieceProvider, string name, int maxPlayers, int maxSpectators, GameRules rule, GameOptions options, string password = null) { if (actionQueue == null) throw new ArgumentNullException("actionQueue"); if (pieceProvider == null) throw new ArgumentNullException("pieceProvider"); if (name == null) throw new ArgumentNullException("name"); if (maxPlayers <= 0) throw new ArgumentOutOfRangeException("maxPlayers", "maxPlayers must be strictly positive"); if (maxSpectators <= 0) throw new ArgumentOutOfRangeException("maxSpectators", "maxSpectators must be strictly positive"); if (options == null) throw new ArgumentNullException("options"); Id = Guid.NewGuid(); _actionQueue = actionQueue; _pieceProvider = pieceProvider; _pieceProvider.Occurancies = () => options.PieceOccurancies; Name = name; CreationTime = DateTime.Now; MaxPlayers = maxPlayers; MaxSpectators = maxSpectators; Rule = rule; Options = options; Password = password; State = GameStates.Created; _specialId = 0; _isSuddenDeathActive = false; _gameStatistics = new Dictionary<string, GameStatisticsByPlayer>(); _winList = new List<WinEntry>(); _suddenDeathTimer = new Timer(SuddenDeathCallback, null, Timeout.Infinite, 0); _voteKickTimer = new Timer(VoteKickCallback, null, Timeout.Infinite, 0); }
public void BasicThreadPoolQueue() { ThreadPoolDispatcher dispatcher = new ThreadPoolDispatcher(); // test CreateQueue - succeeds IActionQueue queue = dispatcher.CreateQueue(); Assert.IsNotNull(queue); // test queuing an action counter = 0; queue.Enqueue(() => { IncrementCounter(Thread.CurrentThread.ManagedThreadId); }); queue.Enqueue(() => { IncrementCounter(Thread.CurrentThread.ManagedThreadId); }); // spin until counter updates while (counter < 2) { Thread.Sleep(0); } // check if a thread failed Assert.IsFalse(failed); // close things out dispatcher.Dispose(); }
private static Guid?GetPrecedingActionFromQueue(IActionQueue queue) { if (queue.OriginalActions != null && queue.OriginalActions.Length > 1) { return(new Guid?(queue.OriginalActions[queue.OriginalActions.Length - 2].Id)); } return(null); }
// in case of ninja promotion, preserving base ninja properties public MasterNinja(IWeapon weapon, IState state, string name, IActionQueue queue) { Name = name; actionQueue = queue; this.state = state; ChangeWeapon(weapon); Console.WriteLine($"Ninja { name } intialized."); }
//default superninja instantiation public MasterNinja(string name) { Name = name; actionQueue = new ActionQueue(); this.state = new StandbyState(this); ChangeWeapon(new Fists()); Console.WriteLine($"Ninja { name } intialized."); }
/// <summary> /// Calls a function on a message queue and returns a task to await the response. /// </summary> /// <param name="actionQueue">The message queue thread.</param> /// <param name="action">The action.</param> /// <returns>A task to await the result.</returns> public static Task RunAsync(this IActionQueue actionQueue, Action action) { return(RunAsync(actionQueue, () => { action(); return true; })); }
/// <summary> /// Add 20 to object counter /// </summary> /// <param name="queue">Queue.</param> private void ThreadWorkerB(IActionQueue queue) { for (int i = 0; i < 10; i++) { counter += 2; Thread.Sleep(0); } }
/// <summary> /// Instantiates the queue configuration. /// </summary> /// <param name="dispatcherQueue"></param> /// <param name="javaScriptQueue"></param> /// <param name="nativeModulesQueue"></param> public ReactQueueConfiguration( IActionQueue dispatcherQueue, IActionQueue javaScriptQueue, IActionQueue nativeModulesQueue) { _dispatcherQueue = dispatcherQueue; _nativeModulesQueue = nativeModulesQueue; _javaScriptQueue = javaScriptQueue; }
public void DispatchAsync(IActionQueue queue, Action <object> action, object userData = null) { ActionItem actionItem = new ActionItem { action = action, userData = userData }; DispatchAsync(queue, actionItem); }
public void DisposeDispatcherFirst() { ManualDispatcher dispatcher = new ManualDispatcher(); IActionQueue queue = dispatcher.CreateQueue(); dispatcher.Dispose(); Assert.IsNull(queue.Dispatcher); ((IDisposable)queue).Dispose(); }
/// <summary> /// Instantiates the <see cref="ReactContextNativeModuleBase"/>. /// </summary> /// <param name="reactContext">The React context.</param> /// <param name="actionQueue">The action queue.</param> protected ReactContextNativeModuleBase(ReactContext reactContext, IActionQueue actionQueue) : base(actionQueue) { if (reactContext == null) { throw new ArgumentNullException(nameof(reactContext)); } Context = reactContext; }
/** Multiplex an EdgeListener using Pathing with the IActionQueue managing the * Rrm. * @param el the EdgeListener to multiplex */ public PathELManager(EdgeListener el, IActionQueue queue) : this(el, false) { PathELManagerAction pema = new PathELManagerAction(this); Action <DateTime> torun = delegate(DateTime now) { queue.EnqueueAction(pema); }; _fe = Brunet.Util.FuzzyTimer.Instance.DoEvery(torun, _period, _period / 2 + 1); }
public void DisposeQueueInsideAction() { ManualDispatcher dispatcher = new ManualDispatcher(); IActionQueue queue = dispatcher.CreateQueue(); queue.Enqueue(() => {}); queue.Enqueue(() => { ((IDisposable)queue).Dispose(); }); queue.Enqueue(() => {}); dispatcher.ProcessQueues(); dispatcher.Dispose(); }
public void DisposeQueueFirst() { ManualDispatcher dispatcher = new ManualDispatcher(); IActionQueue queue = dispatcher.CreateQueue(); string name = queue.Name; ((IDisposable)queue).Dispose(); Assert.IsNull(queue.Dispatcher); Assert.IsNull(dispatcher.GetQueueByName(name)); dispatcher.Dispose(); }
public void SimpleLambda() { ManualDispatcher dispatcher = new ManualDispatcher(); IActionQueue queue = dispatcher.CreateQueue(); int localCounter = 0; for (int i = 0; i < 10; i++) { queue.Enqueue(() => { localCounter += 1; }); } dispatcher.ProcessQueues(); Assert.IsTrue(localCounter == 10); }
internal Event RemoveActionFromPendingActionQueue(Event masterToCleanup, Guid actionId) { Event @event = new Event { Id = masterToCleanup.Id, ChangeKey = masterToCleanup.ChangeKey }; IActionQueue actionQueue = @event; actionQueue.ActionsToRemove = new Guid[] { actionId }; return(this.ExecuteOnMasterWithConflictRetries((Event theEvent) => this.Scope.EventDataProvider.Update(theEvent, null), @event, false)); }
public MonitoringJobExecutor(IActionQueue queue, ILogger logger) { _logger = logger; _queue = queue; //не придумала, как безопасно обработать уже существующие в очереди задачи, //если они были добавлены до старта обработчика и подписки на событие добавления задачи, //поэтому очистка очереди, если она была непустой if (_queue.Count > 0) { _queue.Clear(); } _queue.OnActionAdded += Work; }
public void SimpleFunction() { ManualDispatcher dispatcher = new ManualDispatcher(); IActionQueue queue = dispatcher.CreateQueue(); counter = 0; for (int i = 0; i < 10; i++) { queue.Enqueue(IncrementCounter); } // all the actions should be processed dispatcher.ProcessQueues(); Assert.IsTrue(counter == 10); }
/// <summary> /// Calls a function on a message queue and returns a task to await the response. /// </summary> /// <typeparam name="T">Type of response.</typeparam> /// <param name="actionQueue">The message queue thread.</param> /// <param name="func">The function.</param> /// <returns>A task to await the result.</returns> public static Task <T> RunAsync <T>(this IActionQueue actionQueue, Func <T> func) { var taskCompletionSource = new TaskCompletionSource <T>(); actionQueue.Dispatch(() => { var result = func(); // TaskCompletionSource<T>.SetResult can call continuations // on the awaiter of the task completion source. Task.Run(() => taskCompletionSource.SetResult(result)); }); return(taskCompletionSource.Task); }
internal void Init(IActionQueue asyncQueue) { //WebSocket的事件不是在当前线程触发的,我们需要自己进行线程调整 m_AsyncActionQueue = asyncQueue; MessageDispatcher.Init(); m_IsWaitStart = true; m_HasLoggedOn = false; m_IsLogining = false; m_IsQueueing = false; m_LastReceiveHeartbeatTime = 0; m_LastQueueingTime = 0; RegisterMsgHandler(JsonMessageID.UserHeartbeat, null, HandleUserHeartbeat); }
public ActionManager(IActionQueue manager) { _actionList = new List<ActionListElement>(); _manager = manager; #if !WP7 if (Environment.ProcessorCount == 1) #endif { _actionExecutingRunningNow = true; // Create the timer callback delegate. System.Threading.TimerCallback cb = new System.Threading.TimerCallback(ProcessTimerEvent); _timer = new System.Threading.Timer(cb, manager, 0, 100); //180 } }
public Client(IFactory factory) { if (factory == null) throw new ArgumentNullException("factory"); _factory = factory; _actionQueue = factory.CreateActionQueue(); _clients = new List<ClientData>(); _gameClients = new List<ClientData>(); _games = new List<GameData>(); _pieceBag = factory.CreatePieceBag(32); _inventory = factory.CreateInventory(10); Assembly entryAssembly = Assembly.GetEntryAssembly(); if (entryAssembly != null) { Version version = entryAssembly.GetName().Version; Version = new Versioning { Major = version.Major, Minor = version.Minor, }; }// else, we suppose SetVersion will be called later, before connecting _state = States.Created; _clientId = Guid.Empty; _lastActionFromServer = DateTime.Now; _timeoutCount = 0; _pieceIndex = 0; _gameTimer = new System.Timers.Timer { Interval = GameTimerIntervalStartValue }; _gameTimer.Elapsed += GameTimerOnElapsed; _cancellationTokenSource = new CancellationTokenSource(); _timeoutTask = Task.Factory.StartNew(TimeoutTask, _cancellationTokenSource.Token); _actionQueue.Start(_cancellationTokenSource); }
protected IGame CreateGame(IActionQueue actionQueue, IPieceProvider pieceProvider, string name, int maxPlayers, int maxSpectators, GameRules rule, GameOptions options, string password = null) { ActionQueue = actionQueue as ActionQueueMock; PieceProvider = pieceProvider as PieceProviderMock; return new Game(actionQueue, pieceProvider, name, maxPlayers, maxSpectators, rule, options, password); }
/** Multiplex an EdgeListener using Pathing with the IActionQueue managing the * Rrm. * @param el the EdgeListener to multiplex */ public PathELManager(EdgeListener el, IActionQueue queue) : this(el, false) { PathELManagerAction pema = new PathELManagerAction(this); Action<DateTime> torun = delegate(DateTime now) { queue.EnqueueAction(pema); }; _fe = Brunet.Util.FuzzyTimer.Instance.DoEvery(torun, _period, _period / 2 + 1); }
/** Multiplex an EdgeListener using Pathing with the IActionQueue managing the * Rrm. * @param el the EdgeListener to multiplex */ public PathELManager(EdgeListener el, IActionQueue queue) : this(el, false) { PathELManagerAction pema_rrm = new PathELManagerAction(this, ReqrepTimeoutChecker); Action<DateTime> torun_rrm = delegate(DateTime now) { queue.EnqueueAction(pema_rrm); }; _rrm_fe = Brunet.Util.FuzzyTimer.Instance.DoEvery(torun_rrm, RRM_PERIOD, (RRM_PERIOD / 2) + 1); PathELManagerAction pema_edge = new PathELManagerAction(this, EdgeTimeoutChecker); Action<DateTime> torun_edge = delegate(DateTime now) { queue.EnqueueAction(pema_edge); }; _edge_fe = Brunet.Util.FuzzyTimer.Instance.DoEvery(torun_edge, EDGE_PERIOD, (EDGE_PERIOD / 2) + 1); }
private ActiveThread(Config config) { _config = config; _RunInContextOf = config.RunInContextOf; _que = ActionQueue.New(); _durables = DurableQueue.New(); _isStartedEvent = new ManualResetEvent(false); _isStoppedEvent = new ManualResetEvent(false); _thr = new Thread(main) { Name = _config.Name }; _counters = Context.Get<ICountersDb>().NewCounters(); _stopFlagIsOn = false; }
public static IActionQueue New(IActionQueue impl) { return new SyncedActionQueue(impl); }
private SyncedActionQueue(IActionQueue impl) { _impl = impl; }
internal void Init(IActionQueue asyncQueue) { //WebSocket的事件不是在当前线程触发的,我们需要自己进行线程调整 m_AsyncActionQueue = asyncQueue; NodeMessageDispatcher.Init(); LobbyMessageInit(); m_IsWaitStart = true; m_HasLoggedOn = false; m_IsLogining = false; m_IsQueueing = false; m_LastHeartbeatTime = 0; m_LastReceiveHeartbeatTime = 0; m_LastQueueingTime = 0; m_LastShowQueueingTime = 0; m_LastConnectTime = 0; }