protected virtual void OnRemoveAssetClick(int id) { ActionQueue.Enqueue(() => { GetDatabaseInstance().Remove(id); EditorGUI.FocusTextInControl(string.Empty); }); }
protected void InvokeActionQueue() { while (ActionQueue.Count > 0) { ActionQueue.Dequeue().Invoke(); } }
protected Task replaceRandomAmount(ActionQueue q, QueueActionEventArgs e) { // Choosing a random value (damage amount in this case) // Clone and start processing for every possibility #if _TREE_DEBUG DebugLog.WriteLine(""); DebugLog.WriteLine("--> Depth: " + e.Game.Depth); #endif double perItemWeight = 1.0 / ((e.Args[RandomAmount.MAX] - e.Args[RandomAmount.MIN]) + 1); for (int i = e.Args[RandomAmount.MIN]; i <= e.Args[RandomAmount.MAX]; i++) { // When cloning occurs, RandomAmount has been pulled from the action queue, // so we can just insert a fixed number at the start of the queue and restart the queue // to effectively replace it var clonedNode = ((ProbabilisticGameNode)e.UserData).Branch(perItemWeight); NodeCount++; clonedNode.Game.ActionQueue.StackPush(i); clonedNode.Game.ActionQueue.ProcessAll(clonedNode); searcher.Visitor(clonedNode, this, e); } #if _TREE_DEBUG DebugLog.WriteLine("<-- Depth: " + e.Game.Depth); DebugLog.WriteLine(""); #endif return(Task.FromResult(0)); }
// MOVE public void MoveCommand(Vector3 target) { // Debug.LogWarning("MOVE COMMAND"); // TODO: summoned minions can contain duplicates... foreach (GameObject minion in summoner.SummonedMinions) { if (minion == null) { continue; } ActionQueue q = minion.GetComponent <ActionQueue>(); // if minion's current action is summon, cancel that action q.CancelSummon(); // tell minion to move to target position q.InsertBeforeCurrent(new MovementAction(minion, target)); } summoner.SummonedMinions.Clear(); //minion.GetComponent<ActionQueue>().IsCurrentInteruptable(); // TODO: Consider spawning 'command feedback', like particles or animation. }
/// <summary> /// Give selected units a move command /// </summary> /// <param name="point">Destination</param> public void MoveSelectedUnitsToPoint(PointF point) { List <ModelComponent> selectedEntities = ((XnaUITestGame)Game).Model.GetSelectionState().SelectedEntities; // Ensure each component is a Unit. bool allAreUnits = true; bool playerEntities = false; foreach (ModelComponent component in selectedEntities) { if (entityBelongsToPlayer(component)) { playerEntities = true; if (!(component is UnitComponent)) { allAreUnits = false; break; } } } if (allAreUnits && playerEntities) { foreach (UnitComponent unit in selectedEntities) { MoveAction moveAction = new MoveAction(point.X, point.Y, getMap(), unit); ActionQueue aq = unit.GetActionQueue(); aq.GetChildren().Clear(); aq.AddChild(moveAction); } } }
public void CanDequeueManually() { var random = new Random(); var max = 1000; var dequeuedCount = random.Next(1, max - 1); var value = 0; var remainder = 0; ActionQueue <int> .Clear(); // Add random number of items to queue. Enumerable.Range(1, max).ToList().ForEach(ActionQueue <int> .Enqueue); // Dequeue a (different and smaller) random number of times. for (var i = 0; i < dequeuedCount; i++) { value = ActionQueue <int> .Dequeue(); } // Work out how many items there should be left in the queue. remainder = max - dequeuedCount; // Make sure we dequeued as many items as expected. Assert.AreEqual(value, dequeuedCount); // Make sure there are as many items left in the queue as expected. Assert.AreEqual(ActionQueue <int> .Count, remainder); }
// WARNING: The Game must not be changing during this, // ie. it is not thread-safe unless the game is inactive public Game CloneState() { var entities = new EntityController(Entities); Game game = entities.FindGame(); // Set references to the new player proxies (no additional cloning) game.Player1 = entities.FindPlayer(1); game.Player2 = entities.FindPlayer(2); if (game.CurrentPlayer != null) { game.CurrentPlayer = (CurrentPlayer.Id == game.Player1.Id ? game.Player1 : game.Player2); } // Generate zones owned by game for (int i = 0; i < 2; i++) { game.Players[i].Deck = new Deck(game, Players[i].Deck.HeroClass, game.Players[i]); } // Clone queue, stack and events game.ActionQueue = ((ActionQueue)ActionQueue.Clone()); game.ActionQueue.Attach(game); // Clone triggers game.ActiveTriggers = ((TriggerManager)ActiveTriggers.Clone()); game.ActiveTriggers.Game = game; // Clone environment game.Environment = (Environment)Environment.Clone(); // Link PowerHistory if (PowerHistory != null) { game.PowerHistory = new PowerHistory(game, this); } #if _GAME_DEBUG DebugLog.WriteLine("Cloned game " + GameId + " => " + game.GameId); #endif return(game); }
static void Main() { Console.WriteLine("Вводите строки."); Console.WriteLine("Для завершения работы введите пустую строку."); Console.WriteLine(); var actionQueue = new ActionQueue<string>(PrintMessage); for (;;) { string line = Console.ReadLine(); if (String.IsNullOrEmpty(line)) { // Даем очереди сигнал закончить обработку actionQueue.EnqueueElement(null); break; } else { foreach (char ch in line) { actionQueue.EnqueueElement(ch.ToString()); } } } }
/// <summary> /// This method demonstrates how to close the device properly using the WinRT Serial API. /// /// When the SerialDevice is closing, it will cancel all IO operations that are still pending (not complete). /// The close will not wait for any IO completion callbacks to be called, so the close call may complete before any of /// the IO completion callbacks are called. /// The pending IO operations will still call their respective completion callbacks with either a task /// cancelled error or the operation completed. /// </summary> private async void CloseCurrentlyConnectedDevice() { if (Device != null) { // Notify callback that we're about to close the device OnDeviceClose?.Invoke(this, DeviceInformation); ActionQueue.Dispose(); Connection.Dispose(); // This closes the handle to the device Device.Dispose(); ActionQueue = null; Connection = null; Device = null; // Save the deviceInformation.Id in case deviceInformation is set to null when closing the // device var deviceName = DeviceInformation.Properties["System.ItemNameDisplay"] as string; await MainPage.Current.Dispatcher.RunAsync( CoreDispatcherPriority.Normal, () => { MainPage.Current.NotifyUser(deviceName + " is closed", NotifyType.StatusMessage); }); } }
public UndoMod() { ActionQueueItem.exceptionHandler = (a, e) => { InvalidateAll(); return(false); }; Queue = new ActionQueue(ModInfo.sa_queueCapacity); WrappersDictionary = new WrappersDictionary(); WrappedBuilding.dictionary = WrappersDictionary; }
public async Task ReactBridge_InvokeCallback() { await JavaScriptHelpers.Run(async (executor, jsQueueThread) => { using (var nativeThread = new ActionQueue(ex => { Assert.Fail(); })) { var bridge = new ReactBridge(executor, new MockReactCallback(), nativeThread); var token = await jsQueueThread.RunAsync(() => { bridge.InvokeCallback(1, new JArray()); return(executor.GetGlobalVariable("CallbackCalls")); }); var expected = new JArray { new JArray { 1, new JArray(), }, }; Assert.That(expected.ToString(Formatting.None), Is.EqualTo(token.ToString(Formatting.None))); } }); }
public async Task ActionQueue_HandlesException() { var exception = new Exception(); var countdown = new CountdownEvent(1); var onError = new Action <Exception>(ex => { Assert.AreSame(exception, ex); countdown.Signal(); }); var uiThread = await CallOnDispatcherAsync(() => new DispatcherActionQueue(onError)); var backgroundThread = new ActionQueue(onError, NewThreadScheduler.Default); var taskPoolThread = new ActionQueue(onError); var queueThreads = new[] { uiThread, backgroundThread, taskPoolThread }; using (new CompositeDisposable(queueThreads)) { countdown.AddCount(queueThreads.Length - 1); foreach (var queueThread in queueThreads) { queueThread.Dispatch(() => { throw exception; }); } Assert.IsTrue(countdown.Wait(5000)); } }
public async Task ActionQueue_IsOnThread() { var thrown = 0; var onError = new Action <Exception>(ex => thrown++); var uiThread = await CallOnDispatcherAsync(() => new DispatcherActionQueue(onError)); var backgroundThread = new ActionQueue(onError, NewThreadScheduler.Default); var taskPoolThread = new ActionQueue(onError); var queueThreads = new[] { uiThread, backgroundThread, taskPoolThread }; using (new CompositeDisposable(queueThreads)) { var countdown = new CountdownEvent(queueThreads.Length); foreach (var queueThread in queueThreads) { queueThread.Dispatch(() => { Assert.IsTrue(queueThread.IsOnThread()); countdown.Signal(); }); } Assert.IsTrue(countdown.Wait(5000)); Assert.AreEqual(0, thrown); } }
public void Abort(AgentAbortReason why) { CurrentAction = null; ActionQueue.Clear(); Logger.Log <Agent>($"{Owner.GetIdentifier()} aborted: {why}"); _behavior?.IaAborted(why); }
public async Task TestImageServiceAsync() { var imageService = ServiceRef.Create <IImageService>(new ImageServiceAsync()); //await imageService.GetOrDownloadAsync("https://myimage"); //Assert.AreEqual(1, imageService.Images.Count); //Assert.AreEqual("https://myimage", imageService.Images[0].Url); //Assert.IsTrue(imageService.Images[0].Data.Length > 0); var callTracer = new SimpleCallMonitorTracer(); ActionQueue.BeginMonitor(callTracer); try { await imageService.GetOrDownloadAsync("https://myimage"); Assert.AreEqual(1, imageService.Images.Count); } finally { ActionQueue.ExitMonitor(callTracer); } }
private void MainLoop() { //启动循环,this.LoopActions数组在启动之后就不再更改,所以EventManager模块应最后启动 var _loopActions = new List <PtiLoopEvent>(); _loopActions.AddRange(this.LoopActions); DateTime now = DateTime.Now; while (!StopLoopMark) { #region 全局Loop模块任务 now = DateTime.Now; foreach (var loopAction in _loopActions) { if (now >= loopAction.NextRunDate) { ActionQueue.Enqueue(loopAction.Action); loopAction.NextRunDate = now.Add(loopAction.Interval); } } #endregion PtiEventer act; while (ActionQueue.TryDequeue(out act)) { act.RunAndWait(this); } Thread.Sleep(100); } StopLoopMark = false; this.WriteInfo("Loop Thread Stopped"); }
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> /// 提供给外部手动执行LUA脚本的接口 /// </summary> public void Initilize() { if (!Directory.Exists(PathConfig.localModLuaFilePath)) { Debug.logger.Log(PathConfig.localModLuaFilePath); Directory.CreateDirectory(PathConfig.localModLuaFilePath); } string[] filePaths = Directory.GetFiles(PathConfig.localModLuaFilePath, "*.txt", SearchOption.AllDirectories); ActionQueue loadQueue = new ActionQueue(); foreach (string path in filePaths) { loadQueue.AddAction((act) => { ResourcesLoaderHelper.Instance.LoadTextResourcesByPath("file:///" + path, (scr, bo) => { if (bo) { luaTableList.Add(LuaManager.luaScrMgr.DoString(scr)[0] as LuaTable); act(); } }); }); } loadQueue.AddAction((act) => { foreach (LuaTable LuaModule in luaTableList) { CallLuaFunction("Init", LuaModule, LuaModule); } }); }
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)); } } }
public void CanGetLatency() { var arr = new List <int>(); ActionQueue <int> .Clear(); // Start processing queue at the rate of one item every 11ms. var t = ActionQueue <int> .Consume(x => { arr.Add(x); Thread.Sleep(11); }); // Arrange to stop processing the queue in 0.1 sec ActionQueue <int> .Cancel(95); // Add ten items. Enumerable.Range(0, 10).ToList().ForEach(ActionQueue <int> .Enqueue); // Wait 0.1 sec. Thread.Sleep(100); var latency = ActionQueue <int> .GetLatencyInMilliseconds(); // Wait 0.1 sec for the extra items to be processed in the event of the cancellation not working. Thread.Sleep(100); Assert.IsTrue(latency >= 100, string.Format("Latency was meant to be >= {0}ms but it was {1}ms.", 100, latency)); }
private void Window_Loaded(object sender, RoutedEventArgs e) { if (ServerManager == null) { ServerManager = ServerManager.Instance; TaskUtils.RunOnUIThreadAsync(() => { // We need to load the set of existing servers, or create a blank one if we don't have any... foreach (var profile in Directory.EnumerateFiles(Config.Default.ConfigPath, "*" + Config.Default.ProfileExtension)) { try { ServerManager.Instance.AddFromPath(profile); } catch (Exception ex) { MessageBox.Show(String.Format(_globalizer.GetResourceString("MainWindow_ProfileLoad_FailedLabel"), profile, ex.Message, ex.StackTrace), _globalizer.GetResourceString("MainWindow_ProfileLoad_FailedTitle"), MessageBoxButton.OK, MessageBoxImage.Exclamation); } } ServerManager.Instance.SortServers(); ServerManager.Instance.CheckProfiles(); }).DoNotWait(); } if (IsStandAloneWindow) { _versionChecker = new ActionQueue(); _versionChecker.PostAction(CheckForUpdates).DoNotWait(); } }
public void CanCancelWithTimestampedConsume() { var arr = new List <Timestamped <int> >(); ActionQueue <int> .Clear(); // Start processing queue at the rate of one item every 11ms. var t = ActionQueue <int> .Consume(x => { arr.Add(x); Thread.Sleep(11); }); // Arrange to stop processing the queue in 0.1 sec ActionQueue <int> .Cancel(95); // Add ten items. Enumerable.Range(0, 10).ToList().ForEach(ActionQueue <int> .Enqueue); // Wait 0.1 sec. Thread.Sleep(100); // Add another hundred items. The consumer should be cancelled before this happens. Enumerable.Range(10, 100).ToList().ForEach(ActionQueue <int> .Enqueue); // Wait 0.1 sec for the extra items to be processed in the event of the cancellation not working. Thread.Sleep(100); Assert.AreEqual(9, arr.Count); }
void VisibleObjectSpotted(GameObject visibleObject) { if (currentlyCapturing == visibleObject) { return; } if (currentlyCapturing != null) { return; } ActionQueue queue = GetComponent <ActionQueue>(); bool capturable = gameObject.GetComponent <Faction>().IsCapturable(visibleObject); if (capturable && queue.IsCurrentInteruptable()) { currentlyCapturing = visibleObject; ConverterBuilding converter = FindObjectOfType <ConverterBuilding>(); queue.InsertBeforeCurrent(new CaptureAction(gameObject, converter.gameObject, visibleObject)); } }
protected async Task replaceRandomChoiceParallel(ActionQueue q, QueueActionEventArgs e) { // Choosing a random entity (minion in this case) // Clone and start processing for every possibility #if _TREE_DEBUG DebugLog.WriteLine(""); DebugLog.WriteLine("--> Depth: " + e.Game.Depth); #endif double perItemWeight = 1.0 / e.Args[RandomChoice.ENTITIES].Count(); await Task.WhenAll( e.Args[RandomChoice.ENTITIES].Select(entity => Task.Run(async() => { // When cloning occurs, RandomChoice has been pulled from the action queue, // so we can just insert a fixed item at the start of the queue and restart the queue // to effectively replace it var clonedNode = ((ProbabilisticGameNode)e.UserData).Branch(perItemWeight); NodeCount++; clonedNode.Game.ActionQueue.StackPush((Entity)clonedNode.Game.Entities[entity.Id]); await clonedNode.Game.ActionQueue.ProcessAllAsync(clonedNode); searcher.Visitor(clonedNode, this, e); }) ) ); #if _TREE_DEBUG DebugLog.WriteLine("<-- Depth: " + e.Game.Depth); DebugLog.WriteLine(""); #endif }
public object restart(object newState, bool clearActions) { if (getError() == null) { throw new InvalidOperationException("Agent does not need a restart"); } Validate(newState); _state = newState; if (clearActions) { _aq.Set(ActionQueue.EMPTY); } else { bool restarted = false; ActionQueue prior = null; while (!restarted) { prior = _aq.Get(); restarted = _aq.CompareAndSet(prior, new ActionQueue(prior._q, null)); } if (prior._q.count() > 0) { ((Action)prior._q.peek()).execute(); } } return(newState); }
public CopyMoveProgress(TVDoc doc, ActionQueue[] todo) { this.mDoc = doc; this.mToDo = todo; this.InitializeComponent(); this.copyTimer.Start(); }
/// <nodoc /> public DeploymentProxyService( ProxyServiceConfiguration configuration, HostParameters hostParameters, IAbsFileSystem fileSystem = null, IClock clock = null, IDeploymentServiceClient client = null) { clock ??= SystemClock.Instance; Configuration = configuration; Root = new AbsolutePath(configuration.RootPath); Clock = clock; ContentCacheRequests = new VolatileMap <(string, string), AsyncLazy <BoolResult> >(Clock); ProxyAddress = new VolatileMap <UnitValue, AsyncLazy <string> >(Clock); Client = client ?? DeploymentLauncherHost.Instance.CreateServiceClient(); HostParameters = hostParameters; DownloadQueue = new ActionQueue(configuration.DownloadConcurrency ?? Environment.ProcessorCount); Store = new FileSystemContentStoreInternal( fileSystem ?? new PassThroughFileSystem(), Clock, DeploymentUtilities.GetCasRootPath(Root), new ConfigurationModel(new ContentStoreConfiguration(new MaxSizeQuota($"{Configuration.RetentionSizeGb}GB"))), settings: new ContentStoreSettings() { TraceFileSystemContentStoreDiagnosticMessages = true, }); }
/// <nodoc /> public VsoSymbolClient(IIpcLogger logger, SymbolConfig config, Client apiClient) { m_logger = logger; m_apiClient = apiClient; m_config = config; m_debugEntryCreateBehavior = config.DebugEntryCreateBehavior; m_cancellationSource = new CancellationTokenSource(); m_counters = new CounterCollection <SymbolClientCounter>(); m_logger.Info(I($"[{nameof(VsoSymbolClient)}] Using symbol config: {JsonConvert.SerializeObject(m_config)}")); m_credentialFactory = new VssCredentialsFactory(pat: null, new CredentialProviderHelper(m => m_logger.Verbose(m)), m => m_logger.Verbose(m)); m_symbolClient = new ReloadingSymbolClient( logger: logger, clientConstructor: CreateSymbolServiceClient); m_nagleQueue = NagleQueue <BatchedSymbolFile> .Create( maxDegreeOfParallelism : m_config.MaxParallelUploads, batchSize : m_config.BatchSize, interval : m_config.NagleTime, processBatch : ProcessBatchedFilesAsync); m_fileUploadQueue = new ActionQueue(m_config.MaxParallelUploads); }
public async Task UIManagerModule_Constants_ViewManagerOverrides() { var context = new ReactContext(); var viewManagers = new List <IViewManager> { new TestViewManager() }; ReactNative.Bridge.DispatcherHelpers.MainDispatcher = Dispatcher.CurrentDispatcher; await DispatcherHelpers.RunOnDispatcherAsync(ReactChoreographer.Initialize); var uiImplementationProvider = new UIImplementationProvider(); using (var actionQueue = new ActionQueue(ex => { })) { var module = await DispatcherHelpers.CallOnDispatcherAsync( () => new UIManagerModule(context, viewManagers, uiImplementationProvider, actionQueue)); var constants = module.Constants.GetMap("Test"); Assert.AreEqual(42, constants.GetMap("directEventTypes").GetValue("otherSelectionChange")); Assert.AreEqual(42, constants.GetMap("directEventTypes").GetMap("topSelectionChange").GetValue("registrationName")); Assert.AreEqual(42, constants.GetMap("directEventTypes").GetMap("topLoadingStart").GetValue("foo")); Assert.AreEqual(42, constants.GetMap("directEventTypes").GetValue("topLoadingError")); } // Ideally we should dispose, but the original dispatcher is somehow lost/etc. // await DispatcherHelpers.RunOnDispatcherAsync(ReactChoreographer.Dispose); }
public void TestImageServiceAsyncMultiple() { var imageService = ServiceRef.Create <IImageService>(new ImageServiceAsync()); var callTracer = new SimpleCallMonitorTracer(); ActionQueue.BeginMonitor(callTracer); try { Task.WaitAll( Enumerable .Range(1, 5) .Select(i => Task.Factory.StartNew(async() => { await imageService.GetOrDownloadAsync("https://myimage" + i); })) .ToArray()); Assert.AreEqual(5, imageService.Images.Count); } finally { ActionQueue.ExitMonitor(callTracer); } }
public async Task TestImageServiceAsync() { var wrappedImageService = new ImageServiceAsync(); var imageService = ServiceRef.Create <IImageService>(wrappedImageService); Assert.IsTrue(ServiceRef.TryGetWrappedObject <ImageServiceAsync>(imageService, out var returnedWrappedObject)); Assert.AreSame(wrappedImageService, returnedWrappedObject); //await imageService.GetOrDownloadAsync("https://myimage"); //Assert.AreEqual(1, imageService.Images.Count); //Assert.AreEqual("https://myimage", imageService.Images[0].Url); //Assert.IsTrue(imageService.Images[0].Data.Length > 0); var callTracer = new SimpleCallMonitorTracer(); ActionQueue.BeginMonitor(callTracer); try { await imageService.GetOrDownloadAsync("https://myimage"); Assert.AreEqual(1, imageService.Images.Count); } finally { ActionQueue.ExitMonitor(callTracer); } }
protected async Task replaceRandomAmountParallel(ActionQueue q, QueueActionEventArgs e) { // Choosing a random value (damage amount in this case) // Clone and start processing for every possibility #if _TREE_DEBUG DebugLog.WriteLine(""); DebugLog.WriteLine("--> Depth: " + e.Game.Depth); #endif double perItemWeight = 1.0 / ((e.Args[RandomAmount.MAX] - e.Args[RandomAmount.MIN]) + 1); await Task.WhenAll( Enumerable.Range(e.Args[RandomAmount.MIN], (e.Args[RandomAmount.MAX] - e.Args[RandomAmount.MIN]) + 1).Select(i => Task.Run(async() => { // When cloning occurs, RandomAmount has been pulled from the action queue, // so we can just insert a fixed number at the start of the queue and restart the queue // to effectively replace it var clonedNode = ((ProbabilisticGameNode)e.UserData).Branch(perItemWeight); NodeCount++; clonedNode.Game.ActionQueue.StackPush(i); await clonedNode.Game.ActionQueue.ProcessAllAsync(clonedNode); searcher.Visitor(clonedNode, this, e); }) ) ); #if _TREE_DEBUG DebugLog.WriteLine("<-- Depth: " + e.Game.Depth); DebugLog.WriteLine(""); #endif }
/// <summary> /// Initializes a new instance of the <see cref="MmoRadar"/> class. /// </summary> public MmoRadar() { this.fiber = new PoolFiber(); this.fiber.Start(); this.channel = new MessageChannel<ItemEventMessage>(ItemEventMessage.CounterEventSend); this.itemPositions = new Dictionary<Item, float[]>(); this.itemSubscriptions = new Dictionary<Item, IDisposable>(); this.actionQueue = new ActionQueue(this, this.fiber); }
public void ActionsArePerformedOrderedByTimeThenByInsertionOrder() { var list = new List<int>(); var queue = new ActionQueue(); queue.Add(() => list.Add(1), 0); queue.Add(() => list.Add(7), 2); queue.Add(() => list.Add(8), 2); queue.Add(() => list.Add(4), 1); queue.Add(() => list.Add(2), 0); queue.Add(() => list.Add(3), 0); queue.Add(() => list.Add(9), 2); queue.Add(() => list.Add(5), 1); queue.Add(() => list.Add(6), 1); queue.PerformActions(1); queue.PerformActions(2); queue.PerformActions(3); if (!list.SequenceEqual(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 })) Assert.Fail("Actions were not performed in the correct order. Actual order was: " + string.Join(", ", list)); }
public void Enqueue_PerformActionAndDispose() { var actionQueue = new ActionQueue<string>(s => Debug.WriteLine(s)); Task[] tasks = new Task[10]; for (int i = 0; i < tasks.Length; ++i) { int taskIndex = i; tasks[i] = Task.Run(() => { for (int j = 0; j < 10; ++j) { actionQueue.Enqueue(string.Format("task {0}; item #{1}", taskIndex, j)); } }); } Task.WaitAll(tasks); actionQueue.Dispose(); }
public override void Update(GameTime gameTime) { var template = ScriptingEngine.Engine.Templates[templateid]; var targetName = templateid + "|" + Counter++; var sprite = CreateSprite(targetName, template.Attribute("sprite").Value); var createTarget = Source as DrawableGameObject; if (createTarget != null) createTarget.Add(sprite); var targetActions = new ActionQueue(); foreach (var action in template.Elements()) { targetActions.Add(ScriptingEngine.Engine.Provider.ProcessTemplate(action, targetName)); } ScriptingEngine.Add(targetName, sprite, targetActions); CollisionEngine.Add(sprite); Finished = true; }
public ActionQueue[] ActionProcessorMakeQueues(ScanListItemList theList) { // Take a single list // Return an array of "ActionQueue" items. // Each individual queue is processed sequentially, but all the queues run in parallel // The lists: // - #0 all the cross filesystem moves, and all copies // - #1 all quick "local" moves // - #2 NFO Generator list // - #3 Downloads (rss torrent, thumbnail, folder.jpg) across Settings.ParallelDownloads lists // We can discard any non-action items, as there is nothing to do for them ActionQueue[] queues = new ActionQueue[4]; queues[0] = new ActionQueue("Move/Copy", 1); // cross-filesystem moves (slow ones) queues[1] = new ActionQueue("Move", 2); // local rename/moves queues[2] = new ActionQueue("Write NFO/pyTivo Meta", 4); // writing XBMC NFO files queues[3] = new ActionQueue("Download", this.Settings.ParallelDownloads); // downloading torrents, banners, thumbnails foreach (ScanListItem sli in theList) { Action action = sli as Action; if (action == null) continue; // skip non-actions if (action is ActionNFO || action is ActionPyTivoMeta) queues[2].Actions.Add(action); else if ((action is ActionDownload) || (action is ActionRSS)) queues[3].Actions.Add(action); else if (action is ActionCopyMoveRename) queues[(action as ActionCopyMoveRename).QuickOperation() ? 1 : 0].Actions.Add(action); } return queues; }
/// <summary> /// Worker method to execute the action on a thread. /// </summary> /// <param name="state">(not used)</param> /// <remarks>corresponds to doRun in Java version</remarks> void ExecuteAction(object state) { try { Var.pushThreadBindings(RT.map(RT.AGENT, _agent)); Agent.Nested = PersistentVector.EMPTY; Exception error = null; try { object oldval = _agent.State; object newval = _fn.applyTo(RT.cons(_agent.State, _args)); _agent.SetState(newval); _agent.notifyWatches(oldval,newval); } catch (Exception e) { error = e; } if (error == null) releasePendingSends(); else { Nested = PersistentVector.EMPTY; if (_agent._errorHandler != null) { try { _agent._errorHandler.invoke(_agent, error); } catch (Exception) { // ignore error handler errors } } if (_agent._errorMode == CONTINUE) error = null; } bool popped = false; ActionQueue next = null; while (!popped) { ActionQueue prior = _agent._aq.Get(); next = new ActionQueue(prior._q.pop(), error); popped = _agent._aq.CompareAndSet(prior, next); } if (error==null && next._q.count() > 0) ((Action)next._q.peek()).execute(); } finally { Nested = null; Var.popThreadBindings(); } }
public ActionQueue[] ActionProcessorMakeQueues(ScanListItemList theList) { // Take a single list // Return an array of "ActionQueue" items. // Each individual queue is processed sequentially, but all the queues run in parallel // The lists: // - #0 all the cross filesystem moves, and all copies // - #1 all quick "local" moves // - #2 NFO Generator list // - #3 Downloads (rss torrent, thumbnail, folder.jpg) across Settings.ParallelDownloads lists // We can discard any non-action items, as there is nothing to do for them ActionQueue[] queues = new ActionQueue[4]; queues[0] = new ActionQueue("Move/Copy", 1); // cross-filesystem moves (slow ones) queues[1] = new ActionQueue("Move", 2); // local rename/moves queues[2] = new ActionQueue("Write Metadata", 4); // writing XBMC NFO files, etc. queues[3] = new ActionQueue("Download", TVSettings.Instance.ParallelDownloads); // downloading torrents, banners, thumbnails foreach (ScanListItem sli in theList) { Action action = sli as Action; if (action == null) continue; // skip non-actions if (action is ActionWriteMetadata) // base interface that all metadata actions are derived from queues[2].Actions.Add(action); else if ((action is ActionDownload) || (action is ActionRSS)) queues[3].Actions.Add(action); else if (action is ActionCopyMoveRename) queues[(action as ActionCopyMoveRename).QuickOperation() ? 1 : 0].Actions.Add(action); else { #if DEBUG System.Diagnostics.Debug.Fail("Unknown action type for making processing queue"); #endif queues[3].Actions.Add(action); // put it in this queue by default } } return queues; }
public EchoActor(ActionQueue queue) { _queue = queue; EchoChannel = new ConsumerChannel<EchoInputModel>(_queue, ProcessRequest); }
void Awake() { DontDestroyOnLoad (this); attrib = new BaseAttrib[Enum.GetValues (typeof(Attributes)).Length]; for (int i=0;i<5;i++) attrib [i] = new BaseAttrib(); equip = new BaseItem[Enum.GetValues (typeof(ItemSlot)).Length]; HitPoints = new float[2]; HitPoints [0] = 30; EnergyPoints = new float[2]; inventory = new Dictionary<int, BaseItem>(); quests = new List<Quest> (); skills = new List<BaseSkill> (); abilities = new List<BaseAbility> (); equip = new BaseItem[9]; actions = new ActionQueue (); }
public SingleScheduledAction(DateTime scheduledAt, ActionQueue queue, Action action) { ScheduledAt = scheduledAt; _queue = queue; _action = action; }
public void Constructor_ActionIsNull_ThrowException() { var actionQueue = new ActionQueue<int>(null); }
public Scriptable() { Actions = new ActionQueue(); }
internal static void WebSocketGetAction(WebSocketBase webSocket, ActionQueue actionQueue, Interop.WebSocket.Buffer[] dataBuffers, ref uint dataBufferCount, out Action action, out BufferType bufferType, out IntPtr actionContext) { Debug.Assert(webSocket != null, "'webSocket' MUST NOT be NULL or INVALID."); Debug.Assert(webSocket.SessionHandle != null && !webSocket.SessionHandle.IsInvalid, "'webSocket.SessionHandle' MUST NOT be NULL or INVALID."); Debug.Assert(dataBufferCount >= 0, "'dataBufferCount' MUST NOT be negative."); Debug.Assert((dataBuffers == null && dataBufferCount == 0) || (dataBuffers != null && dataBufferCount == dataBuffers.Length), "'dataBufferCount' MUST MATCH 'dataBuffers.Length'."); action = Action.NoAction; bufferType = BufferType.None; actionContext = IntPtr.Zero; IntPtr dummy; ThrowIfSessionHandleClosed(webSocket); int errorCode; try { errorCode = Interop.WebSocket.WebSocketGetAction(webSocket.SessionHandle, actionQueue, dataBuffers, ref dataBufferCount, out action, out bufferType, out dummy, out actionContext); } catch (ObjectDisposedException innerException) { throw ConvertObjectDisposedException(webSocket, innerException); } ThrowOnError(errorCode); webSocket.ValidateNativeBuffers(action, bufferType, dataBuffers, dataBufferCount); Debug.Assert(dataBufferCount >= 0); Debug.Assert((dataBufferCount == 0 && dataBuffers == null) || (dataBufferCount <= dataBuffers.Length)); }
public ScheduledAction Schedule(TimeSpan interval, ActionQueue queue, Action action) { var scheduled = new SingleScheduledAction(GetScheduledTime(interval), queue, action); Schedule(scheduled); return scheduled; }
public TimerActionScheduler(ActionQueue queue) { _queue = queue; }
public ScheduledAction Schedule(TimeSpan interval, TimeSpan periodicInterval, ActionQueue queue, Action action) { SingleScheduledAction scheduled = null; scheduled = new SingleScheduledAction(GetScheduledTime(interval), queue, () => { try { action(); } catch (Exception ex) { _log.Error(ex); } finally { scheduled.ScheduledAt = GetScheduledTime(periodicInterval); Schedule(scheduled); } }); Schedule(scheduled); return scheduled; }
private static void DrainActionQueue(SafeHandle webSocketHandle, ActionQueue actionQueue) { Debug.Assert(webSocketHandle != null && !webSocketHandle.IsInvalid, "'webSocketHandle' MUST NOT be NULL or INVALID."); IntPtr actionContext; IntPtr dummy; Action action; BufferType bufferType; while (true) { Interop.WebSocket.Buffer[] dataBuffers = new Interop.WebSocket.Buffer[1]; uint dataBufferCount = 1; int errorCode = Interop.WebSocket.WebSocketGetAction(webSocketHandle, actionQueue, dataBuffers, ref dataBufferCount, out action, out bufferType, out dummy, out actionContext); if (!Succeeded(errorCode)) { Debug.Assert(errorCode == 0, "'errorCode' MUST be 0."); return; } if (action == Action.NoAction) { return; } Interop.WebSocket.WebSocketCompleteAction(webSocketHandle, actionContext, 0); } }