public async Task <IEnumerable <Order> > GetAllOrdersAsync(int skip = 0) { using (HttpClient client = GetClient()) { Dictionary <string, string> values = new Dictionary <string, string>() { { "skip", skip.ToString() } }; FormUrlEncodedContent encodedContent = new FormUrlEncodedContent(values); string param = await encodedContent.ReadAsStringAsync().ConfigureAwait(false); HttpResponseMessage httpResponseMessage = await _opQueue.Enqueue(10, () => client.GetAsync(OrdersUrl + "?" + param)).ConfigureAwait(false); httpResponseMessage.EnsureSuccessStatusCode(); string content = await httpResponseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); JObject jsonObject = JObject.Parse(content); string ordersJson = jsonObject["results"].ToString(); IEnumerable <Order> orders = JsonConvert.DeserializeObject <IEnumerable <Order> >(ordersJson); List <Task> tasks = new List <Task>(); foreach (Order order in orders) { tasks.Add(GetItemsByOrderNumberAsync(order.OrderNumber).ContinueWith((antecedent) => { order.Items = new List <Item>(antecedent.Result); })); } await Task.WhenAll(tasks).ConfigureAwait(false); return(orders); } }
public void Enqueue(Operation operation) { if (!(operation is Operation) || operation.Callback is null) { var result = new OperationResult() { Operation = operation }; OnOperationTriggered(result, new ArgumentException($"{nameof(operation)} is not valid or callback is null")); return; } try { OperationQueue?.Enqueue(operation); _resetEvent.Set(); } catch (Exception ex) { OnOperationTriggered(new OperationResult() { Operation = operation }, ex); } }
void PacketHandler() { new Thread(() => { while (!Disposed) { try { if (PacketQueue.TryDequeue(out Packet packet)) { OperationQueue.Enqueue(new Operation(GetPeer(packet.EndPoint), packet)); } else { PacketQueueBegin.Reset(); PacketQueueBegin.WaitOne(); } } catch (Exception e) { OnException(e); } } Console.WriteLine("Packet manager disposed"); }).Start(); }
public async Task AddTaskAsync(TaskViewModel task, string key, int priority = 1) { if (_taskSourceList.Items.Any(x => x.Description == task.Description)) { _logger.LogWarning($@"已跳过重复任务:{task.Description}"); return; } _taskSourceList.Add(task); await _taskQueue.Enqueue(priority, key, task.StartAsync); }
/// <summary> /// 开始下载,若获取大小失败,则会抛出异常 /// </summary> public async ValueTask DownloadAsync(CancellationToken token) { StatusSubject.OnNext(@"正在获取下载文件大小..."); FileSize = await GetContentLengthAsync(token); //总大小 TempDir = EnsureDirectory(TempDir); var list = GetFileRangeList(); var opQueue = new OperationQueue(1); Current = 0; Last = 0; try { using var speedMonitor = CreateSpeedMonitor(); StatusSubject.OnNext(@"正在下载..."); await list.Select(info => // ReSharper disable once AccessToDisposedClosure opQueue.Enqueue(1, () => GetStreamAsync(info, token)) .ToObservable() .SelectMany(res => WriteToFileAsync(res.Item1, res.Item2, token)) ).Merge(); StatusSubject.OnNext(@"下载完成,正在合并文件..."); Current = 0; await MergeFilesAsync(list, token); } catch (OperationCanceledException) { StatusSubject.OnNext(@"下载已取消"); throw; } catch (Exception ex) { _logger.LogError(ex, @"下载出错"); StatusSubject.OnNext(@"下载出错"); } finally { await opQueue.ShutdownQueue(); opQueue.Dispose(); Task.Run(async() => { foreach (var range in list) { await DeleteFileWithRetryAsync(range.FileName); } }, CancellationToken.None).NoWarning(); } }
/// <summary> /// Handles messages received by the service /// whenever the service encounters an error. /// </summary> /// <param name="ex">The exception received from the service.</param> public void HandleServiceError(Exception ex) { OperationQueue.Enqueue(new Action <IServiceMonitor>(serviceMonitor => { try { serviceMonitor.HandleServiceError(ex); } catch (Exception errorHandlerException) { throw new ErrorHandlerException(errorHandlerException.Message, errorHandlerException); } })); }
public async Task <ContentDialogResult> SafeShowAsync(int priority = 1, ContentDialogResult defaultResult = ContentDialogResult.None) { return(await _queue.Enqueue(priority, TaskQueueKeyConstants.ContentDialogKey, async() => { var res = defaultResult; try { await Dispatcher.Invoke(async() => { Owner !.Focus(); res = await ShowAsync(); }); } catch (InvalidOperationException) { } return res; }));
public async Task <FullTrackData> UpdateServerMetaData(CloudNode node) { var success = await MetaDataQueue.Enqueue(5, () => updateServerMetaData(node)); return(success); }
/// <summary> /// Handles notifications from the service that occur /// on an interval to indicate that the service is /// still running. /// </summary> public void HandleServiceHeartbeat() { OperationQueue.Enqueue(new Action <IServiceMonitor>(serviceMonitor => serviceMonitor.HandleServiceHeartbeat())); }
/// <summary> /// Handles messages sent by a client. /// </summary> /// <param name="args">Arguments provided by the client.</param> public void HandleClientMessage(string[] args) { OperationQueue.Enqueue(new Action <IServiceMonitor>(serviceMonitor => serviceMonitor.HandleClientMessage(args))); }
/// <summary> /// Sends a notification. /// </summary> /// <param name="subject">Subject matter for the notification.</param> /// <param name="message">Brief message for the notification.</param> /// <param name="details">Detailed message for the notification.</param> /// <param name="notificationType">One of the <see cref="NotificationTypes"/> values.</param> public void SendNotification(string subject, string message, string details, NotificationTypes notificationType) { OperationQueue.Enqueue(new Notification(subject, message, details, notificationType)); }
private void Enqueue(DispatchPriority priority, int value = 0) { _queue.Enqueue(priority, () => _dequeuedValue = value); }
/// <summary> /// <see cref="IMetadataProvider.Refresh()"/>es the <see cref="IMetadataProvider.Metadata"/> using the specified <paramref name="provider"/> from the loaded metadata provider <see cref="AdapterLoader{T}.Adapters"/>. /// </summary> /// <param name="provider">Name of the <see cref="IMetadataProvider"/> to use for the <see cref="IMetadataProvider.Refresh()"/>.</param> public void RefreshOne(string provider) { OperationQueue.Enqueue(provider); }
/// <summary> /// <see cref="IMetadataProvider.Refresh()"/>es the <see cref="IMetadataProvider.Metadata"/> using all loaded metadata provider <see cref="AdapterLoader{T}.Adapters"/>. /// </summary> public void RefreshAll() { OperationQueue.Enqueue(null); }
public static Task Enqueue(this OperationQueue operationQueue, Func <Task> asyncOperation) => operationQueue.Enqueue(1, asyncOperation);