/// <summary> /// Since all operations accessing 3D resources must be done by the 3D thread, /// this allows other threads to /// send commands to execute in the 3D thread. For example, you might need another thread to be able to /// create, move, and delete BlSprites. You can also use this for general thread safety of various operations. /// This method blocks until the command has executed. /// Also see BlWindow3D and the (non-blocking) #EnqueueCommand for more details. /// </summary> /// <param name="cmd"></param> public void EnqueueCommandBlocking(Command cmd) { // don't bother queuing it if we are already in the window thread if (Graphics.CreationThread == Thread.CurrentThread.ManagedThreadId) { cmd(this); } else // we have to queue it because we aren't in the window thread { var myEvent = new AutoResetEvent(false); var Qcmd = new QueueCommand() { command = cmd, evnt = myEvent }; try { QueueMutex.WaitOne(); Queue.Enqueue(Qcmd); } finally { QueueMutex.ReleaseMutex(); } myEvent.WaitOne(); } }
/// <summary> /// 通讯方法 /// </summary> public void Communication() { try { while (true) { CommandToValue ctov = null; if (QueueCommand.Count > 0 && QueueCommand.TryPeek(out ctov))//有动作命令 { while ((!ExeCommand(ctov))) { Thread.Sleep(90); } QueueCommand.TryDequeue(out ctov); } //else //{ // //发送查询命令 // Tcpsocket.Send(readbytelist.ToArray()); // Thread.Sleep(300); //} } } catch (Exception ex) { Clear(); } }
/// <summary> /// Since all operations accessing 3D resources must be done by the 3D thread, /// this allows other threads to /// send commands to execute in the 3D thread. For example, you might need another thread to be able to /// create, move, and delete BlSprites. You can also use this for general thread safety of various operations. /// This method does not block. /// Also see BlWindow3D and the (blocking) #EnqueueCommandBlocking for more details. /// </summary> /// <param name="cmd"></param> public void EnqueueCommand(Command cmd) { var Qcmd = new QueueCommand() { command = cmd }; // don't bother queuing it if we are already in the window thread if (Graphics.CreationThread == Thread.CurrentThread.ManagedThreadId) { cmd(this); } else // we have to queue it because we aren't in the window thread { try { QueueMutex.WaitOne(); Queue.Enqueue(Qcmd); } finally { QueueMutex.ReleaseMutex(); } } }
private void ThreadMain() { while (!threadStopped) { QueueCommand item = default(QueueCommand); bool hasHandler = false; queueCounter.WaitOne(); lock (queueLock) { if (queue.Count > 0) { item = queue.Dequeue(); hasHandler = true; } } Thread.MemoryBarrier(); if (hasHandler && !threadStopped) { handler(item.Command); } Thread.MemoryBarrier(); } queueDone.Set(); }
/// <summary> /// Since all operations accessing 3D resources must be done by the 3D thread, /// this allows other threads to /// send commands to execute in the 3D thread. For example, you might need another thread to be able to /// create, move, and delete BlSprites. You can also use this for general thread safety of various operations. /// This method blocks until the command has executed or the timeout has expired. /// Also see BlWindow3D and the (non-blocking) #EnqueueCommand for more details. /// </summary> /// <param name="cmd">A command to perform in the window thread, or null if you only want to wait a frame</param> /// <returns>True if BlWindow completed command within timeoutMs milliseconds</returns> public bool EnqueueCommandBlocking(Command cmd = null, int timeoutMs = int.MaxValue) { // don't bother queuing it if we are already in the window thread if (Graphics.CreationThread == Thread.CurrentThread.ManagedThreadId) { cmd(this); return(true); } else // we have to queue it because we aren't in the window thread { var myEvent = new AutoResetEvent(false); var Qcmd = new QueueCommand() { command = cmd, evnt = myEvent }; try { lock (QueueMutex) { Queue.Enqueue(Qcmd); } } catch { } return(myEvent.WaitOne(timeoutMs)); } }
/// <summary> /// Since all operations accessing 3D resources must be done by the 3D thread, /// this allows other threads to /// send commands to execute in the 3D thread. For example, you might need another thread to be able to /// create, move, and delete BlSprites. You can also use this for general thread safety of various operations. /// This method does not block. /// Also see BlWindow3D and the (blocking) #EnqueueCommandBlocking for more details. /// </summary> /// <param name="cmd">A command to perform in the window thread</param> public void EnqueueCommand(Command cmd) { var Qcmd = new QueueCommand() { command = cmd }; // don't bother queuing it if we are already in the window thread if (Graphics.CreationThread == Thread.CurrentThread.ManagedThreadId) { if (cmd != null) { cmd(this); } } else // we have to queue it because we aren't in the window thread { try { lock (QueueMutex) { Queue.Enqueue(Qcmd); } } catch { } } }
public void Queue_Execute_ReturnsEmpty() { var command = new QueueCommand(_helpContextService.Object, _console, LoggerMock.GetLogger <QueueCommand>().Object); var resultMessage = command.Execute(); Assert.Equal("", resultMessage); }
public void EnqueueCommand(QueueCommand Command) { lock (queue) { queue.Enqueue(Command); processQueue.Set(); } }
public static Task <QueueCommandResult> Enqueue(this IServiceProvider services, ID commandID, ICommandMessage message) { Command c = new Command(commandID, message); IContext context = services.GetRequiredService <IContext>(); QueueCommand qc = new QueueCommand(c, context); return(services.Send <QueueCommand, Task <QueueCommandResult> >(qc).To <ICommandProcessor>()); }
private async Task <QueueCommandResult> Handle(QueueCommand m) { TaskQueueItem item = new ExecuteCommandTaskQueueItem(_processor, m.Command, m.Context.Persist()); await Services .Send <Enqueue, Task>(new Enqueue(item)) .To <ITaskQueue>(); return(QueueCommandResult.SuccessfullyQueued(item.Completion)); }
/// <summary> /// 通讯方法 /// </summary> public void Communication() { try { while (true) { CommandToValue ctov = null; LogHelper.WriteSendAGVMessLog($"{this.DeviceID}号AGV 当前线程{Thread.CurrentThread.ManagedThreadId}"); ///因为考虑到发送指令判断返回状态,需要在发送指令前将读取指令 /// 返回的状态指令消耗调,所以应该判断一下缓存中是否有指令 if (QueueCommand.Count > 0 && Tcpsocket.Available > 0) { ///如果缓存区有数据应该将数据消耗完 /// 否则再发送执行指令返回的指令则不知道是执行指令 /// 返回的还是发送读取指令返回的 GetCallBack(); } else if (QueueCommand.Count > 0 && QueueCommand.TryPeek(out ctov))//有动作命令 { while ((!ExeCommand(ctov))) { Thread.Sleep(200); } QueueCommand.TryDequeue(out ctov); } else { //查询心跳指令告知在地标上的信息 SetBitComand(); //发送查询命令 string SenDLog = ""; foreach (byte item in readbytelist) { SenDLog += ((int)item).ToString("X") + " "; } byte[] arr = new byte[] { readbytelist[4], readbytelist[3] }; Int16 SendPackIndex = BitConverter.ToInt16(arr, 0); LogHelper.WriteSendAGVMessLog("报文序号:" + SendPackIndex.ToString() + "发送--心跳--AGV" + this.DeviceID.ToString() + "命令" + ":" + SenDLog); while (!SendExeCommand(readbytelist)) { LogHelper.WriteSendAGVMessLog("报文序号:" + SendPackIndex.ToString() + "发送--心跳--AGV" + this.DeviceID.ToString() + "未成功,等待200ms再发送"); Thread.Sleep(200); } Thread.Sleep(100); } } } catch (Exception ex) { LogHelper.WriteSendAGVMessLog($"{this.DeviceID}号AGV Communication 异常:" + ex.Message); //Clear(); //ReConnect(); } }
public void Save(QueueCommand queue) { var _queue = BindQueue(queue); if (_queue.QueueId.Equals(0)) { _queue = repository.Insert(_queue); } else { repository.Save(_queue); } }
public IActionResult Post([FromBody] QueueCommand user) { try { queueService.Save(user); } catch { return(BadRequest("Queue was not updated")); } return(Ok("Queue was successfuly saved")); }
/// <summary> /// Since all operations accessing 3D resources must be done by the 3D thread, /// this allows other threads to /// send commands to execute in the 3D thread. For example, you might need another thread to be able to /// create, move, and delete BlSprites. You can also use this for general thread safety of various operations. /// This method does not block. /// Also see BlWindow3D and the (blocking) #EnqueueCommandBlocking for more details. /// </summary> /// <param name="cmd"></param> public void EnqueueCommand(Command cmd) { var Qcmd = new QueueCommand() { command = cmd }; try { QueueMutex.WaitOne(); Queue.Enqueue(Qcmd); } finally { QueueMutex.ReleaseMutex(); } }
private Queue BindQueue(QueueCommand queue) { return(new Queue { QueueId = queue.QueueId.HasValue ? queue.QueueId.Value : 0, RestaurantId = queue.RestaurantId, Status = queue.Status, Phone = queue.Phone, ETA = queue.ETA.HasValue ? queue.ETA : DateTime.Now.AddMinutes(30), DateCanceled = queue.DateCanceled, DateFinished = queue.DateFinished }); }
public void Communication() { try { while (true) { CommandToValue ctov = null; if (QueueCommand.Count > 0 && Tcpsocket.Available > 0) { ///如果缓存区有数据应该将数据消耗完 /// 否则再发送执行指令返回的指令则不知道是执行指令 /// 返回的还是发送读取指令返回的 GetCallBack(); } else if (QueueCommand.Count > 0 && QueueCommand.TryPeek(out ctov))//有动作命令 { while ((!ExeCommand(ctov))) { Thread.Sleep(500); } QueueCommand.TryDequeue(out ctov); } else { /* * 发送查询命令 */ SetReadByteList(); Tcpsocket.Send(readbytelist.ToArray());//发送字节 Thread.Sleep(50); GetCallBack(); Thread.Sleep(500); } } } catch (Exception ex) { //LogHelper.WriteErrorLog(ex); //Clear(); //ReConnect(); } }
/// <summary> /// Since all operations accessing 3D resources must be done by the 3D thread, /// this allows other threads to /// send commands to execute in the 3D thread. For example, you might need another thread to be able to /// create, move, and delete BlSprites. You can also use this for general thread safety of various operations. /// This method blocks until the command has executed. /// Also see BlWindow3D and the (non-blocking) #EnqueueCommand for more details. /// </summary> /// <param name="cmd"></param> public void EnqueueCommandBlocking(Command cmd) { var myEvent = new AutoResetEvent(false); var Qcmd = new QueueCommand() { command = cmd, evnt = myEvent }; try { QueueMutex.WaitOne(); Queue.Enqueue(Qcmd); } finally { QueueMutex.ReleaseMutex(); } myEvent.WaitOne(); }
public void AddToQueue(Action action, bool replace, int id) { if (replace) { int queueSize = 0; lock (queueLock) { QueueCommand newCommand = new QueueCommand(); List <QueueCommand> l = new List <QueueCommand> (); foreach (QueueCommand command in queue) { if (command.KeepInQueue && command.Id != id) { l.Add(command); } } queue.Clear(); foreach (QueueCommand command in l) { queue.Enqueue(command); } newCommand.KeepInQueue = false; newCommand.Command = action; newCommand.Id = id; queue.Enqueue(newCommand); queueSize = l.Count + 1; } queueCounter.Release(queueSize); } else { lock (queueLock) { QueueCommand newCommand = new QueueCommand(); newCommand.KeepInQueue = true; newCommand.Command = action; queue.Enqueue(newCommand); } queueCounter.Release(); } Console.WriteLine(queue.Count); }
public void AddToQueue (Action action, bool replace, int id) { if (replace) { int queueSize = 0; lock (queueLock) { QueueCommand newCommand = new QueueCommand (); List<QueueCommand> l = new List<QueueCommand> (); foreach (QueueCommand command in queue) { if (command.KeepInQueue && command.Id != id) l.Add (command); } queue.Clear (); foreach (QueueCommand command in l) { queue.Enqueue (command); } newCommand.KeepInQueue = false; newCommand.Command = action; newCommand.Id = id; queue.Enqueue (newCommand); queueSize = l.Count + 1; } queueCounter.Release (queueSize); } else{ lock (queueLock) { QueueCommand newCommand = new QueueCommand (); newCommand.KeepInQueue = true; newCommand.Command = action; queue.Enqueue (newCommand); } queueCounter.Release(); } Console.WriteLine(queue.Count); }
public Queue Insert(QueueCommand queue) { var _queue = BindQueue(queue); return(repository.Insert(_queue)); }
static void Main(string[] args) { string url = "irc.chat.twitch.tv"; int port = 80; string user = "******"; string oAuthToken = System.IO.File.ReadAllText(@"token.txt"); // token.txt must be in the same folder as EXE string channel = "lobosjr"; //Set up one IrcClient, only one is required it allows better cooldown managerment and traffic will //never cause this code to run slower then any twitch cool down for bots. TwitchClientFactory icf = new TwitchClientFactory(); ITwitchClient client = icf.create(url, port, user, oAuthToken, channel, 600, new OperationRequestEventRaiser(), new PrivMessageEventRaiser(), new WhisperMessageEventRaiser()); client.DefaultMessageHandler += (o, e) => { Console.WriteLine(string.Format("System: {0}", e.Raw)); }; //Set up Legacy Item -> IEquipment converter. LegacyItemEquipmentConverter liec = new LegacyItemEquipmentConverter(); //Set up Equipment repository, if legacy then this will load all items from old files and convert them //into IEquipment in memory. IEquipmentRepository equipmentRepository = LegacyEquipmentRepository .getInstance(liec, LegacyEquipmentRepository.LEGACY_ITEM_BRIDGE_FILE_PATH, LegacyEquipmentRepository.LEGACY_ITEM_PREFIX_FILE_PATH); //Set up Player Repository, Factory and default ILevelObservers ILevelObserver levelUpNotifier = new LevelupNotifier(client); PlayerFactory pf = new PlayerFactory(3, 20, levelUpNotifier); ILevelObserver classChoiceNotifier = new ClassChoiceNotifier(client, pf, 3); pf.GetCurrentDefaultObservers().Add(classChoiceNotifier); IPlayerRepository playerRepo = LegacyPlayerRepository.getInstance(3, 20, pf, equipmentRepository, LegacyPlayerRepository.LEGACY_USER_COINS_FILE_PATH, LegacyPlayerRepository.LEGACY_USER_XP_FILE_PATH, LegacyPlayerRepository.LEGACY_USER_CLASS_FILE_PATH, "players.json"); //Set up Adventure repository. IAdventureRepository adventureRepository = LegacyAdventureRepository .getInstance(LegacyAdventureRepository.LEGACY_DUNGEON_BRIDGE_FILE_PATH, LegacyAdventureRepository.LEGACY_DUNGEON_FILE_PATH_PREFIX, equipmentRepository); //Set up Adventure manager who's Run() func should be used to run adventures on a daemon thread IAdventureManager adventureManager = new AdventureManager(client, 3); new Thread(() => { Thread.CurrentThread.Name = "Adventure Manager"; Thread.CurrentThread.IsBackground = true; adventureManager.Run(); }).Start(); //Set up Party Pool, this keeps track of current parties. IPartyPool partyPool = new PartyPool(client); //Set up Group finder, use the current adventure managers queue. Decide party size capacity for // group finder. GroupFinderFactory gff = new GroupFinderFactory(); IGroupFinder groupFinder = gff.Create(partyPool, 3, adventureRepository, adventureManager); //Set up FutureTask Registry which will keep track of time based operations FutureTaskRegistry futureTaskRegistry = new FutureTaskRegistry(); //Set up Custom Command Factory and Repository for the Command Manager allowing //for saved custom commands to be used aswell as providing capability for new //custom commands to be created from chat(broadcaster/mod only). CustomCommandFactory ccf = new CustomCommandFactory(); CustomCommandRepository ccr = new CustomCommandRepository(); CommandManager commandManager = new CommandManager(client, ccf, ccr); //Initialise all commands to be added to the command manager, seperated by //the source of the request, either PRVMSG or WHISPER. #region Initialisation of Commands #region General Commands UptimeCommand uptime = new UptimeCommand(); Command <IPrivRequest> broadcasting = new BroadcastingFlagCommand(user, playerRepo, pf, uptime, client, futureTaskRegistry, 1, 3, 2, TimeSpan.FromMinutes(30)); Command <IPrivRequest> time = new TimeCommand(); Command <IPrivRequest> playlist = new PlaylistCommand("http://open.spotify.com/user/1251282601/playlist/2j1FVSjJ4zdJiqGQgXgW3t"); Command <IPrivRequest> opinion = new OpinionCommand(); Command <IPrivRequest> pun = new PunCommand(); Command <IPrivRequest> quote = new QuoteCommand(); Command <IPrivRequest> raffle = new RaffleCommand(client, 5, futureTaskRegistry); #endregion #region RPG Commands #region General Command <IWhisperRequest> stats = new StatsCommand(pf, playerRepo); Command <IWhisperRequest> inventory = new InventoryCommand(pf, playerRepo); Command <IWhisperRequest> item = new ItemCommand(equipmentRepository, pf, playerRepo); Command <IWhisperRequest> equip = new EquipCommand(equipmentRepository, pf, playerRepo); Command <IWhisperRequest> unequip = new UnequipCommand(equipmentRepository, pf, playerRepo); Command <IWhisperRequest> shop = new ShopCommand(); Command <IWhisperRequest> classChoice = new ClassChoice(pf, playerRepo, 3); Command <IWhisperRequest> gloat = new GloatCommand(client, pf, playerRepo); Command <IWhisperRequest> respec = new RespecCommand(pf, playerRepo); Command <IWhisperRequest> daily = new DailyCommand(pf, playerRepo); Command <IWhisperRequest> queue = new QueueCommand(groupFinder, pf, playerRepo); Command <IWhisperRequest> leaveQueue = new LeaveQueueCommand(groupFinder, pf, playerRepo); Command <IWhisperRequest> queueTime = new QueueTimeCommand(groupFinder, pf, playerRepo); #endregion #region Party Commands Command <IWhisperRequest> createParty = new CreatePartyCommand(partyPool, pf, playerRepo); Command <IWhisperRequest> pendingInvite = new PendingInvite(partyPool, pf, playerRepo); Command <IWhisperRequest> leaveParty = new LeavePartyCommand(pf, playerRepo); #region Party Leader Commands Command <IWhisperRequest> partyAdd = new AddPartyCommand(client, pf, playerRepo); Command <IWhisperRequest> partyKick = new KickPartyCommand(client, pf, playerRepo); Command <IWhisperRequest> partyStart = new StartPartyCommand(groupFinder, pf, playerRepo); Command <IWhisperRequest> partyPromote = new PromotePartyCommand(client, pf, playerRepo); #endregion #endregion #region Broadcaster only Command <IWhisperRequest> addPlayerXp = new AddPlayerXP(pf, playerRepo); Command <IWhisperRequest> addPlayerCoin = new AddPlayerCoin(pf, playerRepo); Command <IWhisperRequest> setPlayerLevel = new SetPlayerLevel(pf, playerRepo); #endregion #endregion #endregion commandManager.AddAll(uptime, broadcasting, time, playlist, opinion, pun, quote, raffle); commandManager.AddAll(stats, inventory, item, equip, unequip, shop, classChoice, gloat, respec, daily, queue, leaveQueue, queueTime, createParty, pendingInvite, leaveParty, partyAdd, partyKick, partyStart, partyPromote, addPlayerXp, addPlayerCoin, setPlayerLevel); //Provide Handles for events raised by client, multiple handles can be added //allow for parsing of PRVMSG chat for mirroring certain messages. #region Client Event Handling client.AddOperationHandler += commandManager.Handle; client.CancelOperationHandler += commandManager.Handle; client.DeleteOperationHandler += commandManager.Handle; client.EditOperationHandler += commandManager.Handle; client.InfoOperationHandler += commandManager.Handle; client.PrivHandler += (o, e) => { Console.WriteLine(string.Format("{0}: {1}", e.User, e.Message)); }; client.PrivRequestHandler += commandManager.Handle; client.WhisperHandler += (o, e) => { Console.WriteLine(string.Format("Whisper {0}: {1}", e.User, e.Message)); }; client.WhisperRequestHandler += commandManager.Handle; #endregion //new thread for sending messages back to twitch server. new Thread(() => { Thread.CurrentThread.Name = "Twitch Client"; Thread.CurrentThread.IsBackground = true; client.Run(); }).Start(); futureTaskRegistry.Run(); }