private static QueueItem MergeQueueItem(QueueItem item1, QueueItem item2) { TreeNode treeNode = new TreeNode(item1.TreeNode, item2.TreeNode); QueueItem queuItem = new QueueItem(treeNode, item1.Priority + item2.Priority); return queuItem; }
public virtual IEnumerable<QueueItem> GetQueue() { var command = new JsonRequest { Method = "listgroups", Params = null }; var response = PostCommand(command.ToJson()); CheckForError(response); var itmes = Json.Deserialize<NzbGetQueue>(response).QueueItems; foreach (var nzbGetQueueItem in itmes) { var queueItem = new QueueItem(); queueItem.Id = nzbGetQueueItem.NzbId.ToString(); queueItem.Title = nzbGetQueueItem.NzbName; queueItem.Size = nzbGetQueueItem.FileSizeMb; queueItem.Sizeleft = nzbGetQueueItem.RemainingSizeMb; var parsedEpisodeInfo = Parser.Parser.ParseTitle(queueItem.Title); if (parsedEpisodeInfo == null) continue; var remoteEpisode = _parsingService.Map(parsedEpisodeInfo, 0); if (remoteEpisode.Series == null) continue; queueItem.RemoteEpisode = remoteEpisode; yield return queueItem; } }
void WindowKeyDown(object sender, KeyEventArgs args) { ListView lv = (ListView)args.Source; ZoneGroup zg = (ZoneGroup)lv.DataContext; ZonePlayer zp = zg.Coordinator; switch (args.Key) { case Key.Delete: // have to make a copy since there will be a callback // each time the queue is modified QueueItem[] delete = new QueueItem[lv.SelectedItems.Count]; lv.SelectedItems.CopyTo(delete, 0); // reverse numeric sort on queue ID Array.Sort(delete, delegate(QueueItem a, QueueItem b) { return Comparer<int>.Default.Compare(a.NumericId, b.NumericId) * -1; }); // deletes must be synchronous & in order to work properly ThreadPool.QueueUserWorkItem(delegate { foreach (QueueItem qi in delete) { zp.AVTransport.RemoveTrackFromQueue(qi.ItemId); } }); args.Handled = true; break; } }
private void DispatchRecord(QueueItem item, Action completionTrigger) { _log.DebugFormat("dispatching update record '{0}'", item.Record.Id); Coroutine.Invoke(_callback, item.Record, new Result()).WhenDone(r => { completionTrigger(); if(r.HasException) { var e = r.Exception; if(item.Attempt <= _maxRetry) { _log.DebugFormat("dispatch of '{0}' failed, sleeping for {1:0.0}s before attempting re-queue", item.Record.Id, _retrySleep.TotalSeconds); item.Attempt++; Async.Sleep(_retrySleep).WhenDone(r2 => { if(!_dispatchQueue.TryEnqueue(item)) { item.Result.Throw(new InvalidOperationException(string.Format("Unable to re-queue '{0}' for retry {1}.", item.Record.Id, item.Attempt))); return; } _log.DebugFormat("re-queued '{0}' for retry {1}", item.Record.Id, item.Attempt); }); } else { _log.DebugFormat("dispatch of '{0}' permanently failed after {1} tries", item.Record.Id, item.Attempt); item.Result.Throw(e); } } else { _log.DebugFormat("finished dispatch of update record '{0}'", item.Record.Id); item.Result.Return(); } }); }
public void CopyTo() { var it0 = new QueueItem {FileName = "filename", Position = 10, Line = 1}; var it1 = new QueueItem(); Assert.IsFalse(it0.Equals(it1)); it0.CopyTo(it1); Assert.IsTrue(it0.Equals(it1)); }
private void Using(Texture texture) { if (!active) throw new Exception("Call Begin first."); if (activeTexture==null || activeTexture.Texture != texture) { if (recycle.Count > 0) { activeTexture=recycle.Dequeue(); activeTexture.Texture=texture; } else activeTexture=new QueueItem(texture); textures.Add(activeTexture); } }
public static void Main() { // Create LinkedQueue and test its methods QueueItem<string> element = new QueueItem<string>("a"); LinkedQueue<string> queue = new LinkedQueue<string>(element); queue.Enqueue(new QueueItem<string>("b")); queue.Enqueue(new QueueItem<string>("c")); queue.Enqueue(new QueueItem<string>("d")); queue.Enqueue(new QueueItem<string>("e")); QueueItem<string> firstElement = queue.Dequeue(); QueueItem<string> newFirstElement = queue.Peek(); int count = queue.Count(); bool hasElement = queue.Contains(new QueueItem<string>("z")); }
public void BeginDrawing() { count = 0; // we use these a lot, and the overall number of textures // remains stable, so recycle them to avoid excess calls into // the native constructor. foreach (var Entry in QueuedTextures) { Entry.Verticies.Clear(); Entry.Texture = null; RecycleQueue.Enqueue(Entry); } QueuedTextures.Clear(); Drawing = true; activeItem = null; }
public void Begin() { if (active) throw new Exception("Already active"); count = 0; // we use these a lot, and the overall number of textures // remains stable, so recycle them to avoid excess calls into // the native constructor. foreach(var tex in textures) { tex.vertices.Clear(); tex.Texture=null; recycle.Enqueue(tex); } textures.Clear(); active = true; activeTexture = null; }
public void addItem(string category, string filename, string url) { // Search for the specified category QueueHead qh = getQH(category); // If it exists... if (qh != null) { // Create a new item QueueItem qi = new QueueItem(); // Assign its data qi.localFilename = filename; qi.URL = url; // Add item to the category qh.items.Add(qi); } }
public char Dequeue() { if (this.last == null) { throw new EmptyQueueException("you are trying to access a non-existent object"); } QueueItem i = this.last; QueueItem j = this.last; while (i.Next != null) { j = i; i = i.Next; } var value = this.first.Value; this.first = j; j.Next = null; return value; }
private void DispatchRecord(QueueItem item, Action completionTrigger) { _log.DebugFormat("dispatching update record '{0}'", item.Record.Id); Coroutine.Invoke(_callback, item.Record, new Result()).WhenDone(r => { completionTrigger(); if(r.HasException) { if(item.Attempt < _maxRetry) { item.Attempt++; if(!_dispatchQueue.TryEnqueue(item)) { item.Result.Throw(new InvalidOperationException(string.Format("Unable to re-queue '{0}' for retry {1}.", item.Record.Id, item.Attempt))); return; } _log.DebugFormat("re-queued '{0}' for retry {1}", item.Record.Id, item.Attempt); return; } item.Result.Throw(r.Exception); } else { _log.DebugFormat("finished dispatch of update record '{0}'", item.Record.Id); item.Result.Return(); } }); }
public void Enqueue(char value, int priority) { QueueItem newItem = new QueueItem(value, priority); if (this.last == null) { this.last = newItem; this.first = newItem; return; } if (this.first.Priority < priority) { this.first = newItem; } if (this.last.Priority >= priority) { QueueItem temp = this.last; this.last = new QueueItem(value, priority); this.last.Next = temp; return; } QueueItem i = this.last; while (i.Next != null) { if (i.Next.Priority >= priority) { break; } i = i.Next; } QueueItem newElement = new QueueItem(value, priority); newElement.Next = i.Next; i.Next = newElement; }
/// <summary> /// 获取图片 /// </summary> /// <param name="url">图片地址</param> /// <param name="action">图片生成后的回调</param> /// <returns>默认图片</returns> public virtual BitmapSource Get( string url, ImageCreateCallback action ) { QueueItem item = new QueueItem() { Action = action, Url = url }; BackgroundWorker worker = null; lock ( _waitingQueue ) { _waitingQueue.Enqueue( item ); if ( !_isThreadActivated ) { _isThreadActivated = true; worker = new BackgroundWorker(); } } if ( worker != null ) { worker.DoWork += ( ( send, ev ) => StartThread() ); worker.RunWorkerCompleted += ( ( s, e ) => { lock ( _waitingQueue ) { _isThreadActivated = false; } } ); worker.RunWorkerAsync(); } return BitmapCache.DEFAULT_IMAGE; }
private static ArrayList prove(Hashtable cases, SelectableSource world, Statement[] goal, int maxNumberOfSteps) { // This is the main routine from euler.js. // cases: Resource (predicate) => IList of Sequent if (world != null) // cache our queries to the world, if a world is provided { world = new SemWeb.Stores.CachedSource(world); } StatementMap cached_subproofs = new StatementMap(); // Create the queue and add the first item. ArrayList queue = new ArrayList(); { QueueItem start = new QueueItem(); start.env = new Hashtable(); start.rule = new Sequent(Statement.All, goal, null); start.src = null; start.ind = 0; start.parent = null; start.ground = new ArrayList(); queue.Add(start); if (Debug) { Console.Error.WriteLine("Euler: Queue: " + start); } } // The evidence array holds the results of this proof. ArrayList evidence = new ArrayList(); // Track how many steps we take to not go over the limit. int step = 0; // Process the queue until it's empty or we reach our step limit. while (queue.Count > 0) { // deal with the QueueItem at the top of the queue QueueItem c = (QueueItem)queue[queue.Count - 1]; queue.RemoveAt(queue.Count - 1); ArrayList g = new ArrayList(c.ground); // have we done too much? step++; if (maxNumberOfSteps != -1 && step >= maxNumberOfSteps) { if (Debug) { Console.Error.WriteLine("Euler: Maximum number of steps exceeded. Giving up."); } return(null); } // if each statement in the body of the sequent has been proved if (c.ind == c.rule.body.Length) { // if this is the top-level sequent being proved; we've found a complete evidence for the goal if (c.parent == null) { EvidenceItem ev = new EvidenceItem(); ev.head = new Statement[c.rule.body.Length]; bool canRepresentHead = true; for (int i = 0; i < c.rule.body.Length; i++) { ev.head[i] = evaluate(c.rule.body[i], c.env); if (ev.head[i].AnyNull) // can't represent it: literal in subject position, for instance { canRepresentHead = false; } } ev.body = c.ground; ev.env = c.env; if (Debug) { Console.Error.WriteLine("Euler: Found Evidence: " + ev); } if (!canRepresentHead) { continue; } evidence.Add(ev); // this is a subproof of something; whatever it is a subgroup for can // be incremented } else { // if the rule had no body, it was just an axiom and we represent that with Ground if (c.rule.body.Length != 0) { g.Add(new Ground(c.rule, c.env)); } // advance the parent being proved and put the advanced // parent into the queue; unify the parent variable assignments // with this one's QueueItem r = new QueueItem(); r.rule = c.parent.rule; r.src = c.parent.src; r.ind = c.parent.ind; r.parent = c.parent.parent; r.env = (Hashtable)c.parent.env.Clone(); r.ground = g; unify(c.rule.head, c.env, r.rule.body[r.ind], r.env, true); r.ind++; queue.Add(r); if (Debug) { Console.Error.WriteLine("Euler: Queue Advancement: " + r); } // The number of live children for this parent is decremented since we are // done with this subproof, but we store the result for later. if (c.parent.solutions == null) { c.parent.solutions = new StatementList(); } c.parent.solutions.Add(evaluate(r.rule.body[r.ind - 1], r.env)); decrementLife(c.parent, cached_subproofs); } // this sequent still has parts of the body left to be proved; try to // find evidence for the next statement in the body, and if we find // evidence, queue up that evidence } else { // this is the next part of the body that we need to try to prove Statement t = c.rule.body[c.ind]; // Try to process this predicate with a user-provided custom // function that resolves things like mathematical relations. // euler.js provides similar functionality, but the system // of user predicates is completely different here. RdfRelation b = FindUserPredicate(t.Predicate); if (b != null) { Resource[] args; Variable[] unifyResult; Resource value = evaluate(t.Object, c.env); if (!c.rule.callArgs.ContainsKey(t.Subject)) { // The array of arguments to this relation is just the subject of the triple itself args = new Resource[] { evaluate(t.Subject, c.env) }; unifyResult = new Variable[1]; if (t.Subject is Variable) { unifyResult[0] = (Variable)t.Subject; } } else { // The array of arguments to this relation comes from a pre-grouped arg list. args = (Resource[])((ICloneable)c.rule.callArgs[t.Subject]).Clone(); unifyResult = new Variable[args.Length]; for (int i = 0; i < args.Length; i++) { if (args[i] is Variable) { unifyResult[i] = (Variable)args[i]; args[i] = evaluate(args[i], c.env); } } } // Run the user relation on the array of arguments (subject) and on the object. if (b.Evaluate(args, ref value)) { // If it succeeds, we press on. // The user predicate may update the 'value' variable and the argument // list array, and so we want to unify any variables in the subject // or object of this user predicate with the values given to us // by the user predicate. Hashtable newenv = (Hashtable)c.env.Clone(); if (t.Object is Variable) { unify(value, null, t.Object, newenv, true); } for (int i = 0; i < args.Length; i++) { if (unifyResult[i] != null) { unify(args[i], null, unifyResult[i], newenv, true); } } Statement grnd = evaluate(t, newenv); if (grnd != Statement.All) // sometimes not representable, like if literal as subject { g.Add(new Ground(new Sequent(grnd, new Statement[0], null), new Hashtable())); } QueueItem r = new QueueItem(); r.rule = c.rule; r.src = c.src; r.ind = c.ind; r.parent = c.parent; r.env = newenv; r.ground = g; r.ind++; queue.Add(r); // Note: Since we are putting something back in for c, we don't touch the life counter on the parent. } else { // If the predicate fails, decrement the life of the parent. if (c.parent != null) { decrementLife(c.parent, cached_subproofs); } } continue; } // t can be proved either by the use of a rule // or if t literally exists in the world Statement t_resolved = evaluate(t, c.env); // If resolving this statement requires putting a literal in subject or predicate position, we // can't prove it. if (t_resolved == Statement.All) { if (c.parent != null) { decrementLife(c.parent, cached_subproofs); } continue; } ArrayList tcases = new ArrayList(); // See if we have already tried to prove this. if (cached_subproofs.ContainsKey(t_resolved)) { StatementList cached_solutions = (StatementList)cached_subproofs[t_resolved]; if (cached_solutions == null) { if (Debug) { Console.Error.WriteLine("Euler: Dropping queue item because we have already failed to prove it: " + t_resolved); } } else { foreach (Statement s in cached_solutions) { if (Debug) { Console.Error.WriteLine("Euler: Using Cached Axiom: " + s); } Sequent seq = new Sequent(s); tcases.Add(seq); } } } else { // get all of the rules that apply to the predicate in question if (t_resolved.Predicate != null && cases.ContainsKey(t_resolved.Predicate)) { tcases.AddRange((IList)cases[t_resolved.Predicate]); } if (cases.ContainsKey("WILDCARD")) { tcases.AddRange((IList)cases["WILDCARD"]); } // if t has no unbound variables and we've matched something from // the axioms, don't bother looking at the world, and don't bother // proving it any other way than by the axiom. bool lookAtWorld = true; foreach (Sequent seq in tcases) { if (seq.body.Length == 0 && seq.head == t_resolved) { lookAtWorld = false; tcases.Clear(); tcases.Add(seq); break; } } // if there is a seprate world, get all of the world // statements that witness t if (world != null && lookAtWorld) { MemoryStore w = new MemoryStore(); if (Debug) { Console.Error.WriteLine("Running " + c); } if (Debug) { Console.Error.WriteLine("Euler: Ask World: " + t_resolved); } world.Select(t_resolved, w); foreach (Statement s in w) { if (Debug) { Console.Error.WriteLine("Euler: World Select Response: " + s); } Sequent seq = new Sequent(s); tcases.Add(seq); } } } // If there is no evidence or potential evidence (i.e. rules) // for t, then we will dump this QueueItem by not queuing any // subproofs. // Otherwise we try each piece of evidence in turn. foreach (Sequent rl in tcases) { ArrayList g2 = (ArrayList)c.ground.Clone(); if (rl.body.Length == 0) { g2.Add(new Ground(rl, new Hashtable())); } QueueItem r = new QueueItem(); r.rule = rl; r.src = rl; r.ind = 0; r.parent = c; r.env = new Hashtable(); r.ground = g2; if (unify(t, c.env, rl.head, r.env, true)) { QueueItem ep = c; // euler path while ((ep = ep.parent) != null) { if (ep.src == c.src && unify(ep.rule.head, ep.env, c.rule.head, c.env, false)) { break; } } if (ep == null) { // It is better for caching subproofs to work an entire proof out before // going on, which means we want to put the new queue item at the // top of the stack. queue.Add(r); c.liveChildren++; if (Debug) { Console.Error.WriteLine("Euler: Queue from Axiom: " + r); } } } } // If we did not add anything back into the queue for this item, then // we decrement the life of the parent. if (c.liveChildren == 0 && c.parent != null) { decrementLife(c.parent, cached_subproofs); } } } return(evidence); }
public void Push(QueueItem item) { // Add an item to our queue, or if it exists, ensure that if anyone wanted us to ignore the file write time, we don't lose that info ImmutableInterlocked.AddOrUpdate(ref _queue, item.FileName, item, (fileName, value) => new QueueItem(fileName, item.SharedInputs, item.TempPEOutputPath, item.IgnoreFileWriteTime | value.IgnoreFileWriteTime)); }
/// <summary> /// Called when we know that we actually shall add the item, and here we can execute processes that takes extra time /// </summary> /// <param name="itm"></param> /// <returns></returns> private bool PrepareQueueItemForAdd(QueueItem itm) { // Ignore control messages if (itm.Headers.ContainsKey(Headers.ControlMessageHeader) && Convert.ToBoolean(itm.Headers[Headers.ControlMessageHeader])) { return(false); } if (itm.Headers.ContainsKey("NServiceBus.MessageId")) { itm.Id = itm.Headers["NServiceBus.MessageId"]; } // Get Messages names if (itm.Headers.ContainsKey("NServiceBus.EnclosedMessageTypes")) { itm.Messages = ExtractEnclosedMessageTypeNames(itm.Headers["NServiceBus.EnclosedMessageTypes"]); } else // Get from Message body { if (itm.Content == null) { LoadMessageContent(itm); } itm.Messages = GetMessageNames(itm.Content, false); } itm.DisplayName = MergeStringArray(itm.Messages).Default(itm.DisplayName).CutEnd(55); // Get process started time if (itm.Headers.ContainsKey("NServiceBus.ProcessingStarted") && itm.Headers.ContainsKey("NServiceBus.ProcessingEnded")) { try { itm.ProcessTime = Convert.ToInt32((Convert.ToDateTime(itm.Headers["NServiceBus.ProcessingEnded"]) - Convert.ToDateTime(itm.Headers["NServiceBus.ProcessingStarted"])).TotalSeconds); } catch (Exception ex) { #if DEBUG Console.WriteLine("Failed to parse NServiceBus.ProcessingStarted, " + ex.Message); #endif } } // Get Error message info if (itm.Headers.ContainsKey("NServiceBus.ExceptionInfo.Message")) { itm.Error = new QueueItemError(); try { itm.Error.State = itm.Queue.Type == QueueType.Error ? QueueItemErrorState.ErrorQueue : QueueItemErrorState.Retry; itm.Error.Message = itm.Headers["NServiceBus.ExceptionInfo.Message"]; if (itm.Headers.ContainsKey("NServiceBus.ExceptionInfo.StackTrace")) { itm.Error.StackTrace = itm.Headers["NServiceBus.ExceptionInfo.StackTrace"]; } if (itm.Headers.ContainsKey(Headers.Retries)) { itm.Error.Retries = Convert.ToInt32(itm.Headers[Headers.Retries]); } //itm.Error.TimeOfFailure = Convert.ToDateTime(itm.Headers.SingleOrDefault(k => k.Key == "NServiceBus.TimeOfFailure").Value); } catch { itm.Error = null; } } return(true); }
private string GetQueueItemContent(QueueItem itm) { return(itm.Content == null || itm.Content.StartsWith("**") ? _mgr.LoadMessageContent(itm) : itm.Content); }
private void miCopyMessageContent_Click(object sender, RoutedEventArgs e) { QueueItem itm = ((MenuItem)sender).Tag as QueueItem; Clipboard.SetData(DataFormats.Text, GetQueueItemContent(itm)); }
private void miReturnErrorMsg_Click(object sender, RoutedEventArgs e) { QueueItem itm = ((MenuItem)sender).Tag as QueueItem; _mgr.MoveErrorMessageToOriginQueue(itm); }
protected override MessageState Send(QueueItem item) { return(Proxy.SendItem(item.BodyStream)); }
internal Boolean Add(Packet pk, IPEndPoint remote) { var count = pk.Total; var ss = Session; ss.StatSend.Increment(count); if (ss.LogSend) { ss.WriteLog("SendAsync [{0}]: {1}", count, pk.ToHex()); } ss.LastTime = DateTime.Now; // 打开UDP广播 if (ss.Local.Type == NetType.Udp && remote != null && Equals(remote.Address, IPAddress.Broadcast)) { ss.Client.EnableBroadcast = true; } // 同时只允许一个异步发送,其它发送放入队列 // 考虑到超长数据包,拆分为多个包 if (count <= BufferSize) { var qi = new QueueItem { Packet = pk, Remote = remote }; _SendQueue.Enqueue(qi); } else { // 数据包切分,共用数据区,不需要内存拷贝 var idx = 0; while (true) { var remain = count - idx; if (remain <= 0) { break; } var len = Math.Min(remain, BufferSize); var qi = new QueueItem { //qi.Packet = new Packet(pk.Data, pk.Offset + idx, len); Packet = new Packet(pk.ReadBytes(idx, len)), Remote = remote }; _SendQueue.Enqueue(qi); idx += len; } } Check(false); return(true); }
void Check(Boolean io) { // 如果已销毁,则停止检查发送队列 if (Session.Client == null || Session.Disposed) { return; } var qu = _SendQueue; if (qu.IsEmpty) { return; } // 如果没有在发送,就开始发送 //if (Interlocked.CompareExchange(ref _Sending, 1, 0) != 0) return; QueueItem qi = null; if (!qu.TryDequeue(out qi)) { return; } SocketAsyncEventArgs se; if (!_seSendPool.TryDequeue(out se)) { var buf = new Byte[BufferSize]; se = new SocketAsyncEventArgs(); se.SetBuffer(buf, 0, buf.Length); se.Completed += (s, e) => Process(e); _seSendPool.Enqueue(se); Session.WriteLog("创建SendSA {0}", 1); } se.RemoteEndPoint = qi.Remote; // 拷贝缓冲区,设置长度 var p = 0; var remote = qi.Remote; // 为了提高吞吐量,减少数据收发次数,尽可能的把发送队列多个数据包合并成为一个大包发出 while (true) { var pk = qi.Packet; var len = pk.Total; if (pk?.Data == null || se.Buffer == null) { break; } pk.WriteTo(se.Buffer, p); p += len; // 不足最大长度,试试下一个 if (!qu.TryPeek(out qi)) { break; } if (qi.Remote + "" != remote + "") { break; } if (p + qi.Packet.Count > BufferSize) { break; } if (!qu.TryDequeue(out qi)) { break; } } try { se.SetBuffer(0, p); } catch (Exception e) { Session.WriteLog("SendSAErr {0}", e.Message); //未测试下面这句 //Check(false); return; } if (!Session.OnSendAsync(se)) { if (io) { Process(se); } else { Task.Factory.StartNew(s => Process(s as SocketAsyncEventArgs), se); } } }
void Check(Boolean io) { // 如果已销毁,则停止检查发送队列 if (Session.Client == null || Session.Disposed) { return; } var qu = _SendQueue; if (qu.Count == 0) { return; } // 如果没有在发送,就开始发送 if (Interlocked.CompareExchange(ref _Sending, 1, 0) != 0) { return; } QueueItem qi = null; if (!qu.TryDequeue(out qi)) { return; } var se = _seSend; if (se == null) { var buf = new Byte[BufferSize]; se = _seSend = new SocketAsyncEventArgs(); se.SetBuffer(buf, 0, buf.Length); se.Completed += (s, e) => Process(e); Session.WriteLog("创建SendSA {0}", 1); } se.RemoteEndPoint = qi.Remote; // 拷贝缓冲区,设置长度 var p = 0; var remote = qi.Remote; // 为了提高吞吐量,减少数据收发次数,尽可能的把发送队列多个数据包合并成为一个大包发出 while (true) { var pk = qi.Packet; var len = pk.Count; Buffer.BlockCopy(pk.Data, pk.Offset, se.Buffer, p, len); p += len; // 不足最大长度,试试下一个 if (!qu.TryPeek(out qi)) { break; } if (qi.Remote + "" != remote + "") { break; } if (p + qi.Packet.Count > BufferSize) { break; } if (!qu.TryDequeue(out qi)) { break; } } se.SetBuffer(0, p); if (!Session.OnSendAsync(se)) { if (io) { Process(se); } else { Task.Factory.StartNew(s => Process(s as SocketAsyncEventArgs), se); } } }
public QueueAck Enqueue(QueueItem message, bool enableException = false) { return(Execute <QueueAck>(message, enableException)); }
public QueueItem(T value, QueueItem <T> previous) : this(value) { previous.Next = this; }
public Project() { Queue = new QueueItem(); Activity = new ProjectActivity(this); }
public void PurgeMessage(QueueItem itm) { _mgr.PurgeMessage(itm); }
/// <summary> /// Dispose the BASS Audio engine. Free all BASS and Visualisation related resources /// </summary> public void DisposeAndCleanUp() { // Clean up BASS Resources try { // Some Winamp dsps might raise an exception when closing BassWaDsp.BASS_WADSP_Free(); } catch (Exception) { } if (Config.MusicPlayer == AudioPlayer.Asio) { BassAsio.BASS_ASIO_Stop(); BassAsio.BASS_ASIO_Free(); } if (Config.MusicPlayer == AudioPlayer.WasApi) { BassWasapi.BASS_WASAPI_Free(); } if (_mixer != null) { _mixer.Dispose(); } for (int i = 0; i < _streams.Count; i++) { if (_streams[i] != null) { _streams[i].Dispose(); } } Bass.BASS_Stop(); Bass.BASS_Free(); _bassFreed = true; foreach (int pluginHandle in DecoderPluginHandles) { Bass.BASS_PluginFree(pluginHandle); } lock (_commandQueueSync) { _commandQueue.Clear(); QueueItem item = new QueueItem(); item.cmd = PlaybackCommand.ExitThread; _commandQueue.Add(item); } _commandNotify.Set(); GUIGraphicsContext.OnNewAction -= new OnActionHandler(OnNewAction); }
protected override void RemoveFinishedTask() { preparingItem = null; }
public abstract void MoveErrorMessageToOriginQueue(QueueItem itm);
protected virtual void InsertQueueItem(int idx, MyBlueprintDefinitionBase blueprint, MyFixedPoint amount) { Debug.Assert(idx <= m_queue.Count); Debug.Assert(CanUseBlueprint(blueprint)); Debug.Assert(amount > 0); QueueItem item = new QueueItem(); item.Amount = amount; item.Blueprint = blueprint; if (CanUseBlueprint(item.Blueprint)) { if (m_queue.IsValidIndex(idx) && m_queue[idx].Blueprint == item.Blueprint) { // Increase amount if there is same kind of item at this index. item.Amount += m_queue[idx].Amount; item.ItemId = m_queue[idx].ItemId; m_queue[idx] = item; } else if (m_queue.Count > 0 && (idx >= m_queue.Count || idx == -1) && m_queue[m_queue.Count - 1].Blueprint == item.Blueprint) { // Add to the last item in the queue if it is the same. item.Amount += m_queue[m_queue.Count - 1].Amount; item.ItemId = m_queue[m_queue.Count - 1].ItemId; m_queue[m_queue.Count - 1] = item; } else { if (idx == -1) idx = m_queue.Count; // Reset timer when adding first item. Otherwise we might produce it faster than possible. if (m_queue.Count == 0) m_lastUpdateTime = MySandboxGame.TotalGamePlayTimeInMilliseconds; // Put new item into the queue with given amount and type. item.ItemId = NextItemId; m_queue.Insert(idx, item); } UpdatePower(); OnQueueChanged(); } }
private void miCopyMessageID_Click(object sender, RoutedEventArgs e) { QueueItem itm = ((MenuItem)sender).Tag as QueueItem; Clipboard.SetData(DataFormats.Text, itm.Id); }
/// <summary> /// upload a file /// </summary> /// <param name="url">requested url</param> /// <param name="httpPostData">post data</param> /// <param name="fileUploadData">file data</param> /// <param name="fileFieldName">file name in header</param> /// <param name="fileName">file name</param> /// <param name="action">callback when finished</param> public void RequestUploadFile(string url, List<KeyValuePair<string, string>> httpPostData, byte[] fileUploadData, string fileFieldName, string fileName, RequestFinished action) { QueueItem item = new QueueItem() { Method = HttpMethod.Post, Action = action, Url = url, PostData = httpPostData }; AddQueueItem(item); }
private void miDeleteMessage_Click(object sender, RoutedEventArgs e) { QueueItem itm = ((MenuItem)sender).Tag as QueueItem; _mgr.PurgeMessage(itm); }
/// <summary> /// Get a task from a queued item /// </summary> /// <param name="item">queue request item</param> /// <returns>task</returns> private HttpTask GetTask(QueueItem item) { HttpTask httpTask = null; if (item.Method == HttpMethod.Get) { httpTask = new GetTextHttpTask(item.Url); } else { httpTask = new PostTextHttpTask(item.Url, item.PostData); } httpTask.HttpRequestCompleted += (state, stream, error) => { lock (_lock) { _tasks.Remove(httpTask); } if (_taskCount == 0) { _resetEvent.Set(); } Interlocked.Increment(ref _taskCount); item.Action(state, stream, error); }; return httpTask; }
public static async System.Threading.Tasks.Task RunAsync([QueueTrigger("orderqueue")] QueueItem <Guid> queueItem, [Table("ordertable")] IQueryable <ExtendedTableEntity <Order> > orderTable, [Table("producttable")] IQueryable <ExtendedTableEntity <Product> > productTable, [Queue("emailqueue")] IAsyncCollector <QueueItem <EmailMessage> > emailQueue, TraceWriter log) { try { var orderEntity = orderTable.Where(x => x.RowKey == queueItem.Value.ToString()).FirstOrDefault(); if (orderEntity != null) { var order = orderEntity.FromTableEntity(); var productEntity = productTable.Where(x => x.RowKey == order.ProductId.ToString()).FirstOrDefault(); if (productEntity != null) { var product = productEntity.FromTableEntity(); var emailBody = $@"<style>body{{font-family:Segoe UI,SegoeUI,Segoe WP,Helvetica Neue,Helvetica,Tahoma,Arial,sans-serif}}</style> <h3>Thank you for your order #{order.OrderId}. Your order has been confirmed.</h3> <table border=""1"" celpadding=""5""> <tr> <th>Product</td> <th>Price</td> <th>Quentity</td> <th>Total</td> </tr> <tr> <td>{product.Name}</td> <td style= ""text-align:right;"">{order.Price}</td> <td style= ""text-align:right;"">{order.Quentity}</td> <td style= ""text-align:right;"">{order.Price * order.Quentity}</td> </tr> </table> <br/><br/> Happy Shopping!"; await emailQueue.AddAsync(new QueueItem <EmailMessage>() { Value = new EmailMessage { From = "*****@*****.**", To = "*****@*****.**", Subject = $"Order Confirmation - #{order.OrderId}", Body = emailBody } }); } else { throw new ApplicationException($"Product ({order.ProductId}) not found."); } } else { throw new ApplicationException($"Order ({queueItem.Value}) not found."); } } catch (Exception ex) { log.Error(ex.ToString()); throw; } }
/// <summary> /// Returns a lock right away or waits asynchronously until a lock is available. /// </summary> /// <returns>Task indicating the task of acquiring the lock.</returns> public Task LockAsync(string operationName) { if (_lockFileWatcher == null) { throw new InvalidOperationException(Resources.Error_AsyncLockNotInitialized); } // See if we can get the lock -- if not then enqueue lock request. if (Lock(operationName)) { return Task.FromResult(true); } QueueItem item = new QueueItem(operationName); _lockRequestQueue.Enqueue(item); return item.HasLock.Task; }
public override Model.QueueFetchResult GetUnprocessedMessages(QueueType type, IEnumerable <QueueItem> currentItems) { var result = new QueueFetchResult(); result.Status = QueueFetchResultStatus.NotChanged; var queues = _monitorQueues.Where(q => q.Queue.Type == type); if (queues.Count() == 0) { result.Items = EMPTY_LIST; return(result); } List <QueueItem> r = new List <QueueItem>(); result.Items = r; foreach (var q in queues) { var azureQueue = q.Main; if (IsIgnoredQueue(q.Queue.Name)) { continue; } try { if (q.HasChanged()) { if (result.Status == QueueFetchResultStatus.NotChanged) { result.Status = QueueFetchResultStatus.OK; } long msgCount = q.GetMessageCount(); if (msgCount > 0) { var msgs = q.Main.PeekBatch(0, SbmqSystem.MAX_ITEMS_PER_QUEUE); result.Count += (uint)msgCount; foreach (var msg in msgs) { QueueItem itm = currentItems.FirstOrDefault(i => i.Id == msg.MessageId); if (itm == null && !r.Any(i => i.Id == msg.MessageId)) { itm = CreateQueueItem(q.Queue, msg); // Load Message names and check if its not an infra-message if (!PrepareQueueItemForAdd(itm)) { itm = null; } } if (itm != null) { r.Insert(0, itm); } } } } } catch (MessagingCommunicationException mce) { OnWarning(mce.Message, null, Manager.WarningType.ConnectonFailed); result.Status = QueueFetchResultStatus.ConnectionFailed; break; } catch (SocketException se) { OnWarning(se.Message, null, Manager.WarningType.ConnectonFailed); result.Status = QueueFetchResultStatus.ConnectionFailed; break; } catch (Exception e) { OnError("Error occured when processing queue " + q.Queue.Name + ", " + e.Message, e, false); result.Status = QueueFetchResultStatus.HasErrors; } } return(result); }
void OnCompleted(QueueItem item) { if (item.controller != null) { item.controller.Dispose(); } lock (queue) queue.Remove(item); OnAnimationCompleted(new AnimationCompletedEventArg { Animation = item.animation, Control = item.control, Mode = item.mode }); }
/// <summary> /// Starts sending response. /// </summary> /// <param name="response">IMAP response.</param> /// <param name="completedAsyncCallback">Callback to be called when this method completes asynchronously.</param> /// <returns>Returns true is method completed asynchronously(the completedAsyncCallback is raised upon completion of the operation). /// Returns false if operation completed synchronously.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>response</b> is null reference.</exception> public bool SendResponseAsync(IMAP_r response,EventHandler<EventArgs<Exception>> completedAsyncCallback) { if(response == null){ throw new ArgumentNullException("response"); } lock(m_pLock){ QueueItem responseItem = new QueueItem(response,completedAsyncCallback); m_pResponses.Enqueue(responseItem); // Start sending response, no active response sending. if(!m_IsSending){ SendResponsesAsync(); } // Response sent synchronously. if(responseItem.IsSent){ return false; } // Response queued or sending is in progress. else{ responseItem.IsAsync = true; return true; } } }
public Task Update(QueueItem item) { return _hubContext.Clients.All.Updated(new QueueUpdate {Id = item.Id, Item = item}); }
protected override void CancelTask() { ++CanceledTasks; preparingItem = null; }
private AzureMessageQueue GetMessageQueue(QueueItem itm) { return(_monitorQueues.Single(i => i.Queue.Type == itm.Queue.Type && i.Queue.Name == itm.Queue.Name)); }
/// <summary>Escreve um QueueItem</summary> private void writeItem( int idx, int order, QueueItem item, HtmlTextWriter writer, int turns, bool queue ) { writer.WriteLine("<td class='resourceCell'><div align='center'>" + order + "</div></td>"); if( ShowDocumentation ) { writer.WriteLine( "<td class='resource'><a class='docs' href='{1}'>{0}</a></td>", info.getContent(item.FactoryName), Wiki.GetUrl(item.Factory.Category, item.Factory.Name) ); } else { writer.WriteLine("<td class='resource'>" + info.getContent(item.FactoryName) + "</td>"); } if( ShowQuantity ) { writer.WriteLine("<td class='resourceCell'>" + item.Quantity + "</td>"); } if( !queue ) { writer.WriteLine("<td class='resourceCell'>+ " + turns + "</td>"); } else { writer.WriteLine("<td class='resourceCell'>{0} (+{1})</td>", info.getContent("waiting"), turns); } string cross = OrionGlobals.getCommonImagePath("remove.gif"); string str = "<a href='javascript:dequeue("+idx+")'><img src='"+cross+"' /></a>"; writer.WriteLine("<td class='resourceManagement'>" + str + "</td>"); }
protected override void SetTask(QueueItem item, TimeSpan?remaining) { Assert.IsNotNull(item); preparingItem = item; }
/// <summary> /// post a new task to the pool. /// </summary> /// <param name="item"></param> private void AddQueueItem(QueueItem item) { BackgroundWorker worker = null; lock (_lock) { _waitingQueue.Enqueue(item); if (!_isThreadActivated) { _isThreadActivated = true; worker = new BackgroundWorker(); } } if (worker != null) { worker.DoWork += ((send, ev) => StartThread()); worker.RunWorkerCompleted += ((s, e) => { lock (_lock) { _isThreadActivated = false; } }); worker.RunWorkerAsync(); } }
internal ExpandResponse QueueExpandNodeRequest(ObjectExplorerSession session, string nodePath, bool forceRefresh = false) { NodeInfo[] nodes = null; TreeNode node = session.Root.FindNodeByPath(nodePath); ExpandResponse response = new ExpandResponse { Nodes = new NodeInfo[] { }, ErrorMessage = node.ErrorMessage, SessionId = session.Uri, NodePath = nodePath }; if (node != null && Monitor.TryEnter(node.BuildingMetadataLock, LanguageService.OnConnectionWaitTimeout)) { try { int timeout = (int)TimeSpan.FromSeconds(settings?.ExpandTimeout ?? ObjectExplorerSettings.DefaultExpandTimeout).TotalMilliseconds; QueueItem queueItem = bindingQueue.QueueBindingOperation( key: bindingQueue.AddConnectionContext(session.ConnectionInfo, connectionName), bindingTimeout: timeout, waitForLockTimeout: timeout, bindOperation: (bindingContext, cancelToken) => { if (forceRefresh) { nodes = node.Refresh().Select(x => x.ToNodeInfo()).ToArray(); } else { nodes = node.Expand().Select(x => x.ToNodeInfo()).ToArray(); } response.Nodes = nodes; response.ErrorMessage = node.ErrorMessage; try { // SMO changes the database when getting sql objects. Make sure the database is changed back to the original one if (bindingContext.ServerConnection.CurrentDatabase != bindingContext.ServerConnection.DatabaseName) { bindingContext.ServerConnection.SqlConnectionObject.ChangeDatabase(bindingContext.ServerConnection.DatabaseName); } } catch (Exception ex) { Logger.Write(LogLevel.Warning, $"Failed to change the database in OE connection. error: {ex.Message}"); // We should just try to change the connection. If it fails, there's not much we can do } return(response); }); queueItem.ItemProcessed.WaitOne(); if (queueItem.GetResultAsT <ExpandResponse>() != null) { response = queueItem.GetResultAsT <ExpandResponse>(); } } catch { } finally { Monitor.Exit(node.BuildingMetadataLock); } } return(response); }
/// <summary> /// get web content /// </summary> /// <param name="url">requested url</param> /// <param name="action">callback when finished</param> public void Request(string url, HttpMethod method, List<KeyValuePair<string, string>> httpPostData, RequestFinished action) { QueueItem item = new QueueItem() { Action = action, Url = url, Method = method, PostData = httpPostData }; AddQueueItem(item); }
void IListenerHandler.DoMessageReceived(QueueItem message) { OnMessageReceived(new GenericEventArgs <QueueItem>(message)); }
private void DoAnimation(QueueItem item) { if(Monitor.TryEnter(item)) try { if (item.controller == null) { item.controller = CreateDoubleBitmap(item.control, item.mode, item.animation, item.clipRectangle); } if (item.controller.IsCompleted) return; item.controller.BuildNextFrame(); } catch { OnCompleted(item); } }
private void RunQueue() { if (Interlocked.CompareExchange(ref runQueueInProgress, 1, 0) == 0) { try { QueueItem firstItemLeftInQueue = null; while (true) { QueueItem queueItemToProcess = null; bool lockTaken = false; try { syncRoot.Enter(ref lockTaken); if (queue.Count > 0) { queueItemToProcess = queue.Peek(); if (queueItemToProcess == firstItemLeftInQueue) { break; } else { queue.Dequeue(); } } else { break; } } finally { if (lockTaken) { syncRoot.Exit(); } } if (!RunItemIfRunnable(false, queueItemToProcess)) { EnqueueItem(queueItemToProcess); System.Diagnostics.Debug.WriteLine("Method {0} still waiting for items {1} become {2}", queueItemToProcess.ToString(), GetWaitedItemNameList(queueItemToProcess), (queueItemToProcess.IsAvailable) ? "available" : "registered"); if (firstItemLeftInQueue == null) { firstItemLeftInQueue = queueItemToProcess; } } else { System.Diagnostics.Debug.WriteLine("Prerequisites of method {0} become {1}, method completed asynchronously", queueItemToProcess.ToString(), (queueItemToProcess.IsAvailable) ? "available" : "registered"); } } } finally { Interlocked.CompareExchange(ref runQueueInProgress, 0, 1); } if (runQueueReenteredDuringProgress) { // reentrance occured, possible new items enqueued; rerun queue runQueueReenteredDuringProgress = false; RunQueue(); } } else { runQueueReenteredDuringProgress = true; } }
/// <summary> /// Adds the contol to animation queue. /// </summary> /// <param name="control">Target control</param> /// <param name="mode">Animation mode</param> /// <param name="parallel">Allows to animate it same time as other animations</param> /// <param name="animation">Personal animation</param> public void AddToQueue(Control control, AnimateMode mode, bool parallel = true, Animation animation = null, Rectangle clipRectangle = default(Rectangle)) { if(animation == null) animation = DefaultAnimation; if (control is IFakeControl) { control.Visible = false; return; } var item = new QueueItem() { animation = animation, control = control, IsActive = parallel, mode = mode, clipRectangle = clipRectangle }; //check visible state switch (mode) { case AnimateMode.Show: if (control.Visible)//already showed { OnCompleted(new QueueItem {control = control, mode = mode}); return; } break; case AnimateMode.Hide: if (!control.Visible)//already hidden { OnCompleted(new QueueItem { control = control, mode = mode }); return; } break; } //add to queue lock (queue) queue.Add(item); lock (requests) requests.Add(item); }
private void ProcessQueueItem(QueueItem item) { m_serializer(item.Pip, item.Mutable); }
public Task AddToQueue(QueueItem item) { return _hubContext.Clients.All.Added(item); }
public override async Task <AddQueueResponse> AddQueueItem(AddQueueRequest request, ServerCallContext context) { AddQueueResponse response = new AddQueueResponse(); QueueItem item = null; switch (request.NewItemCase) { case AddQueueRequest.NewItemOneofCase.Item: item = response.Item = request.Item; break; case AddQueueRequest.NewItemOneofCase.TweetId: ITweet tweet = await TweetAsync.GetTweet(request.TweetId); item = new QueueItem(); item.TweetId = tweet.Id; item.Played = 0; item.User = _dataStore.GetUser(tweet.CreatedBy.Id); item.Created = tweet.CreatedAt .ToUniversalTime() .ToTimestamp(); StringBuilder builder = new StringBuilder("<speak>"); ISet <IUserMentionEntity> users = new HashSet <IUserMentionEntity>(tweet.UserMentions); if (tweet.IsRetweet) { ITweet retweeted = tweet.RetweetedTweet; builder.AppendFormat("I, {0} retweetet {1}:", tweet.CreatedBy.Name, tweet.CreatedBy.Id == retweeted.CreatedBy.Id ? "myself" : retweeted.CreatedBy.Name); builder.Append("<break time=\"500ms\"/>"); builder.Append(retweeted.FullText); foreach (var userMention in retweeted.UserMentions) { users.Add(userMention); } } else if (tweet.QuotedTweet != null) { ITweet quoted = tweet.QuotedTweet; builder.AppendFormat("I, {0} quoted {1}: ", tweet.CreatedBy.Name, tweet.CreatedBy.Id == quoted.CreatedBy.Id ? "myself" : quoted.CreatedBy.Name); builder.Append("<break time=\"500ms\"/>"); builder.Append(quoted.FullText); builder.Append("<break time=\"500ms\"/>"); builder.AppendFormat("My quote on that: {0}", tweet.FullText); foreach (var userMention in quoted.UserMentions) { users.Add(userMention); } } else { builder.AppendFormat("I, {0} tweeted: ", tweet.CreatedBy.Name); builder.Append(tweet.FullText); } builder.Append("<break time=\"1s\"/>"); builder.Append("</speak>"); string text = _urlRegex.Replace(builder.ToString(), ""); if (string.IsNullOrWhiteSpace(text)) { response.IsEmpty = true; break; } foreach (var user in users) { text = text.Replace($"@{user.ScreenName}", user.Name); } item.Ssml = HttpUtility.HtmlDecode(text); item.Content = HttpUtility.HtmlDecode(tweet.FullText); response.Item = item; break; } if (!response.IsEmpty) { _logger.LogInformation("Added Item {0} by {1}", item.TweetId, item.User.Handle); _dataStore.Enqueue(item); } return(response); }
/// <summary> /// This method creates any entity records that this sample requires. /// Create a queue record. /// Create a letter record. /// Create a queue item for queue record. /// Retrieves new owner's details. /// Update the queue item record to assign it to new owner. /// </summary> public void CreateRequiredRecords() { // Create a private queue instance and set its property values. Queue newQueue = new Queue { Name = "Example Queue.", Description = "This is an example queue.", QueueViewType = new OptionSetValue((int)QueueQueueViewType.Private) }; // Create a new queue and store its returned GUID in a variable // for later use. _queueId = _serviceProxy.Create(newQueue); Console.WriteLine("Created {0}.", newQueue.Name); Letter newLetter = new Letter { Description = "Example Letter" }; _letterId = _serviceProxy.Create(newLetter); Console.WriteLine("Created {0}.", newLetter.Description); // Create a new instance of a queueitem and initialize its // properties. QueueItem item = new QueueItem { QueueId = new EntityReference(Queue.EntityLogicalName, _queueId), ObjectId = new EntityReference(Letter.EntityLogicalName, _letterId) }; // Create the queueitem on the server, which will associate // the letter with the queue. _queueItemId = _serviceProxy.Create(item); Console.WriteLine("Created the letter queue item for the queue."); //<snippetRemoveQueueItemWorker2> // Retrieve the user information. WhoAmIRequest whoAmIRequest = new WhoAmIRequest(); WhoAmIResponse whoAmIResponse = (WhoAmIResponse)_serviceProxy.Execute( whoAmIRequest); ColumnSet columnSet = new ColumnSet("fullname"); SystemUser currentUser = (SystemUser)_serviceProxy.Retrieve( SystemUser.EntityLogicalName, whoAmIResponse.UserId, columnSet); String currentUserName = currentUser.FullName; //</snippetRemoveQueueItemWorker2> // Create an instance of an existing queueitem in order to specify // the user that will be working on it. QueueItem queueItem = new QueueItem { QueueItemId = _queueItemId, WorkerId = new EntityReference(SystemUser.EntityLogicalName, whoAmIResponse.UserId) }; _serviceProxy.Update(queueItem); Console.WriteLine("The letter queue item is queued for new owner {0}.", currentUserName); return; }
public abstract string LoadMessageContent(QueueItem itm);
/// <summary> /// Stopping Playback /// </summary> public override void Stop() { lock (_syncRoot) { if (_mixer == null) { Log.Debug("BASS: Already stopped. Don't execute Stop a second time"); return; } lock (_commandQueueSync) { QueueItem item = new QueueItem(); item.cmd = PlaybackCommand.Stop; _commandQueue.Add(item); } _commandNotify.Set(); } _commandRegistered.Wait(); }
public abstract void PurgeMessage(QueueItem itm);