/// <summary> /// Notifies all channels that the channel is being removed (usually due to the application shutting down). /// <para>Each channel runs on its own thread, and this method calls a method of the same name on each specific channel instance all at once, which in /// turn queues the request to run on the thread specific to that channel. You can use the "await" operator to block the calling thread until the /// request completes for all channels.</para> /// </summary> /// <param name="timeout">An optional timeout value (in milliseconds).</param> public Task Closing(int timeout = -1) { var tasks = new List <Task>(_Channels.Count); foreach (Channel channel in _Channels) { tasks.Add(channel.Closing(timeout)); } return(TaskEx.WhenAll(tasks)); }
// ------------------------------------------------------------------------------------------------------- /// <summary> /// Initializes all channels that are not yet initialized. /// <para>Each channel runs on its own thread, and this method calls a method of the same name on each specific channel instance all at once, which in /// turn queues the request to run on the thread specific to that channel. You can use the "await" operator to block the calling thread until the /// request completes for all channels.</para> /// </summary> /// <param name="timeout">An optional timeout value (in milliseconds).</param> public Task Initialize() { var tasks = new List <Task>(_Channels.Count); foreach (Channel channel in _Channels) { tasks.Add(channel.Initialize()); } return(TaskEx.WhenAll(tasks)); }
public static async Task <Result> Combine(this IEnumerable <Task <Result> > tasks, string errorMessageSeparator) { #if NET40 Result[] results = await TaskEx.WhenAll(tasks).ConfigureAwait(Result.DefaultConfigureAwait); #else var results = await Task.WhenAll(tasks) .ConfigureAwait(Result.DefaultConfigureAwait); #endif return(results.Combine(errorMessageSeparator)); }
private async Task OpenAsync(ICollection <Uri> source) { Debug.WriteLine("SmMediaManager.OpenAsync() state " + State); State = MediaManagerState.Opening; ++_openCount; ResetCancellationToken(); Task <IMediaReader>[] readerTasks = null; Exception exception; try { _mediaStreamConfigurator.Initialize(); _readerManager = await _segmentReaderManagerFactory.CreateAsync(new SegmentManagerParameters() { Source = source }, ContentType, _playbackCancellationTokenSource.Token).ConfigureAwait(false); if (null == _readerManager) { Debug.WriteLine("SmMediaManager.OpenAsync() unable to create reader manager"); SetMediaState(MediaManagerState.Error, "Unable to create reader"); return; } else { readerTasks = _readerManager.SegmentManagerReaders.Select(CreateReaderPipeline).ToArray(); _readers = await TaskEx.WhenAll <IMediaReader>(readerTasks).ConfigureAwait(false); foreach (IMediaReader mediaReader in _readers) { mediaReader.IsEnabled = true; } TimeSpan timeSpan = await _readerManager.StartAsync(_playbackCancellationTokenSource.Token).ConfigureAwait(false); _mediaStreamConfigurator.MediaManager = (this); StartReaders(); return; } } catch (OperationCanceledException ex) { SetMediaState(MediaManagerState.Error, "Media play canceled"); exception = ex; } catch (Exception ex) { Debug.WriteLine("SmMediaManager.OpenAsync() failed: " + ex.Message); SetMediaState(MediaManagerState.Error, "Unable to play media"); exception = new AggregateException(ex.Message, ex); } await CleanupFailedOpenAsync(readerTasks); throw exception; }
/// <summary> /// upload file to azure blob /// </summary> /// <param name="taskId">Task id</param> /// <param name="filePath">local file path</param> /// <param name="blob">destination azure blob object</param> internal virtual async Task Upload2Blob(long taskId, IStorageBlobManagement localChannel, string filePath, StorageBlob.CloudBlob blob) { string activity = String.Format(Resources.SendAzureBlobActivity, filePath, blob.Name, blob.Container.Name); string status = Resources.PrepareUploadingBlob; ProgressRecord pr = new ProgressRecord(OutputStream.GetProgressId(taskId), activity, status); FileInfo fileInfo = new FileInfo(filePath); DataMovementUserData data = new DataMovementUserData() { Data = blob, TaskId = taskId, Channel = localChannel, Record = pr, TotalSize = fileInfo.Length }; await DataMovementTransferHelper.DoTransfer(() => { return(this.TransferManager.UploadAsync(filePath, blob, null, this.GetTransferContext(data), this.CmdletCancellationToken)); }, data.Record, this.OutputStream); if (this.BlobProperties != null || this.BlobMetadata != null) { await TaskEx.WhenAll( this.SetBlobProperties(localChannel, blob, this.BlobProperties), this.SetBlobMeta(localChannel, blob, this.BlobMetadata)); } try { await localChannel.FetchBlobAttributesAsync( blob, AccessCondition.GenerateEmptyCondition(), this.RequestOptions, this.OperationContext, this.CmdletCancellationToken); } catch (StorageException e) { //Handle the limited read permission. if (!e.IsNotFoundException()) { throw; } } WriteCloudBlobObject(data.TaskId, localChannel, blob); }
// ------------------------------------------------------------------------------------------------------- /// <summary> /// Immediately stops and closes all channel threads. A terminate request is send to all channels at once, with a default 5 second timeout before the /// channel threads are forcibly aborted. /// <para>Note: If exiting an application process, best practice is to call 'ICEController.Shutdown()'.</para> /// <para>Each channel runs on its own thread, and this method calls a method of the same name on each specific channel instance all at once, which in /// turn queues the request to run on the thread specific to that channel. This method doesn't return until all channels are closed.</para> /// </summary> /// <param name="timeout">The amount of time for each individual channel thread to finish up before it is forced to terminate. Specify -1 to wait indefinitely.</param> public async void Terminate(int timeout = ICEController.DEFAULT_TERMINATE_TIMEOUT) { List <Task> tasks = new List <Task>(_Channels.Count); foreach (Channel channel in _Channels) { tasks.Add(channel.Terminate(timeout)); } await TaskEx.WhenAll(tasks); }
private Task SendWithAwaitAll(TItem item) { var tasks = new Task[_targets.Count()]; var targetNum = 0; foreach (var target in _targets) { tasks[targetNum++] = target.SendAsync(item); } return(TaskEx.WhenAll(tasks)); }
/// <summary> /// Sets the result to the given value. Multiple results /// will be combined accordingly. /// </summary> /// <param name="value">The resulting task.</param> public void SetResult(Task value) { if (_result != null) { _result = TaskEx.WhenAll(_result, value); } else { _result = value; } }
public async Task <ActionResult> FetchAsynchronouslyParallel() { var resultItems = new List <Headline>(); var allTasks = from newsSource in _newsSources select FetchHeadlinesTaskAsync(newsSource); Headline[][] results = await TaskEx.WhenAll(allTasks); return(View("results", results.SelectMany(x => x))); }
private Task SendEachInThreadPoolWithAwaitAll(TItem item) { var tasks = new Task[_targets.Count()]; var targetNum = 0; foreach (var target in _targets) { var target1 = target; tasks[targetNum++] = TaskEx.Run(() => target1.SendAsync(item)); } return(TaskEx.WhenAll(tasks)); }
private async Task CloseCleanupAsync() { Debug.WriteLine("SmMediaManager.CloseCleanupAsync()"); List <Task> tasks = new List <Task>(); ISegmentReaderManager readerManager = this._readerManager; if (null != readerManager) { this._readerManager = (ISegmentReaderManager)null; tasks.Add(readerManager.StopAsync()); } IMediaStreamConfigurator msc = this._mediaStreamConfigurator; if (null != msc) { tasks.Add(msc.CloseAsync()); } if (this._readers != null && this._readers.Length > 0) { tasks.Add(this.CloseReadersAsync()); } if (null != this._playTask) { tasks.Add(this._playTask); } if (tasks.Count > 0) { while (Enumerable.Any <Task>((IEnumerable <Task>)tasks, (Func <Task, bool>)(t => !t.IsCompleted))) { try { Task t = TaskEx.Delay(2500); Debug.WriteLine("SmMediaManager.CloseCleanupAsync() waiting for tasks"); Task task = await TaskEx.WhenAny(t, TaskEx.WhenAll((IEnumerable <Task>)tasks)).ConfigureAwait(false); Debug.WriteLine("SmMediaManager.CloseCleanupAsync() finished tasks"); } catch (Exception ex) { Debug.WriteLine("SmMediaManager.CloseCleanupAsync() play task failed: " + ExceptionExtensions.ExtendedMessage(ex)); } } } if (null != msc) { msc.MediaManager = (IMediaManager)null; } this.DisposeReaders(); if (null != readerManager) { DisposeExtensions.DisposeSafe((IDisposable)readerManager); } }
/// <summary> /// Get the config instance for the namespace. </summary> /// <param name="namespaces"> the namespaces of the config, order desc. </param> /// <returns> config instance </returns> public static async Task <IConfig> GetConfig(IEnumerable <string> namespaces) { if (namespaces == null) { throw new ArgumentNullException(nameof(namespaces)); } #if NET40 return(new MultiConfig(await TaskEx.WhenAll(namespaces.Reverse().Distinct().Select(GetConfig)).ConfigureAwait(false))); #else return(new MultiConfig(await Task.WhenAll(namespaces.Reverse().Distinct().Select(GetConfig)).ConfigureAwait(false))); #endif }
public static async Task <Result <K> > Combine <T, K>(this IEnumerable <Task <Result <T> > > tasks, Func <IEnumerable <T>, K> composer, string errorMessageSeparator) { #if NET40 IEnumerable <Result <T> > results = await TaskEx.WhenAll(tasks).ConfigureAwait(Result.DefaultConfigureAwait); #else IEnumerable <Result <T> > results = await Task.WhenAll(tasks).ConfigureAwait(Result.DefaultConfigureAwait); #endif return(results.Combine(composer, errorMessageSeparator)); }
public async Task UpdateUniqueValueKeyTest() { var tableName = RandomTableNameName(); Console.WriteLine($"Table name for this test: {tableName}"); var service = new TableStorageUniqueService(connString, tableName); service.Init(); const string ContractorVatNrInCountryForCompanyAccount = "ContractorVatNrInCountryForCompanyAccount"; var companyAccountId = Guid.NewGuid(); var countryCode = "PL"; var vatNumber = "8971649500"; var contractorId = new TestId(Guid.NewGuid()); var value = String.Format("{0}:{1}:{2}", companyAccountId.ToString("N"), countryCode, vatNumber); var id = await service.GetOrAddUniqueValueKey(ContractorVatNrInCountryForCompanyAccount, value, contractorId); if (!id.Equals(contractorId)) { Assert.Fail(); } var updatedValue = String.Format("{0}:{1}:{2}", companyAccountId.ToString("N"), countryCode, "8971649501"); var id2 = await service.UpdateUniqueValueKey(ContractorVatNrInCountryForCompanyAccount, value, updatedValue, contractorId, 5); if (!id2.Equals(contractorId)) { Assert.Fail(); } var contractorId2 = new TestId(Guid.NewGuid()); var task1 = service.UpdateUniqueValueKey(ContractorVatNrInCountryForCompanyAccount, updatedValue, value, contractorId, 5); var task2 = service.GetOrAddUniqueValueKey(ContractorVatNrInCountryForCompanyAccount, value, contractorId2); var t = await TaskEx.WhenAll(task1, task2); if (!t.Item1.Equals(contractorId)) { Assert.Fail(); } if (t.Item2.Equals(contractorId2)) { Assert.Fail(); } }
public static async Task <Result <IEnumerable <T> > > Combine <T>(this Task <IEnumerable <Task <Result <T> > > > task, string errorMessageSeparator) { var tasks = await task.ConfigureAwait(Result.DefaultConfigureAwait); #if NET40 var results = await TaskEx.WhenAll(tasks).ConfigureAwait(Result.DefaultConfigureAwait); #else var results = await Task.WhenAll(tasks).ConfigureAwait(Result.DefaultConfigureAwait); #endif return(results.Combine(errorMessageSeparator)); }
public async Task DownloadFiles(bool bForce = false) { List <Task> tasks = new List <Task>(); tasks.Add(DownloadFile(Config.Region == Config.RegionDef.UK ? CinemasUKFileName : CinemasIEFileName, bForce)); tasks.Add(DownloadFile(Config.Region == Config.RegionDef.UK ? FilmsUKFileName : FilmsIEFileName, bForce)); tasks.Add(DownloadFile(Config.Region == Config.RegionDef.UK ? FilmCinemasUKFileName : FilmCinemasIEFileName, bForce)); #if WINDOWS_PHONE && !WP8 await TaskEx.WhenAll(tasks); #else await Task.WhenAll(tasks); #endif }
private async Task CloseCleanupAsync() { Debug.WriteLine("SmMediaManager.CloseCleanupAsync()"); List <Task> tasks = new List <Task>(); ISegmentReaderManager readerManager = _readerManager; if (null != readerManager) { _readerManager = null; tasks.Add(readerManager.StopAsync()); } IMediaStreamConfigurator msc = _mediaStreamConfigurator; if (null != msc) { tasks.Add(msc.CloseAsync()); } if (_readers != null && _readers.Length > 0) { tasks.Add(CloseReadersAsync()); } if (null != _playTask) { tasks.Add(_playTask); } if (tasks.Count > 0) { while (tasks.Any(t => !t.IsCompleted)) { try { Task t = TaskEx.Delay(2500); Debug.WriteLine("SmMediaManager.CloseCleanupAsync() waiting for tasks"); Task task = await TaskEx.WhenAny(t, TaskEx.WhenAll(tasks)).ConfigureAwait(false); Debug.WriteLine("SmMediaManager.CloseCleanupAsync() finished tasks"); } catch (Exception ex) { Debug.WriteLine("SmMediaManager.CloseCleanupAsync() play task failed: " + ex.ExtendedMessage()); } } } if (null != msc) { msc.MediaManager = null; } DisposeReaders(); readerManager?.DisposeSafe(); }
public override Task <DocumentAndNavigationInfo> GetDocument() { if (string.IsNullOrEmpty(id)) { var query = templateQuery.Clone(); query.Start = itemIndex; query.PageSize = 1; return(DatabaseCommands.QueryAsync(indexName, query, null) .ContinueWith( t => { var info = PopulateDocumentOrConflictsFromDocuments( t.Result.Results.Select(r => r.ToJsonDocument())); info.TotalDocuments = t.Result.TotalResults; info.Index = itemIndex; info.ParentPath = GetParentPath(); info.UrlForFirst = GetUrlForIndex(0); info.UrlForPrevious = itemIndex > 0 ? GetUrlForIndex(itemIndex - 1) : null; info.UrlForNext = itemIndex < t.Result.TotalResults - 1 ? GetUrlForIndex(itemIndex + 1) : null; info.UrlForLast = GetUrlForIndex(t.Result.TotalResults - 1); return info; })); } var getDocumentTask = DatabaseCommands.GetAsync(id); var getStatisticsTask = QueryIndexForDocument(); return(TaskEx.WhenAll(getDocumentTask, getStatisticsTask) .ContinueWith(_ => { var info = PopulateDocumentOrConflictsFromTask(getDocumentTask, id); info.Index = itemIndex; info.TotalDocuments = getStatisticsTask.Result.TotalResults; info.ParentPath = GetParentPath(); info.UrlForFirst = GetUrlForIndex(0); info.UrlForPrevious = itemIndex > 0 ? GetUrlForIndex(itemIndex - 1) : null; info.UrlForNext = itemIndex < getStatisticsTask.Result.TotalResults - 1 ? GetUrlForIndex(itemIndex + 1) : null; info.UrlForLast = GetUrlForIndex(getStatisticsTask.Result.TotalResults - 1); return info; } )); }
/// <summary> /// upload file to azure blob /// </summary> /// <param name="taskId">Task id</param> /// <param name="filePath">local file path</param> /// <param name="blob">destination azure blob object</param> internal virtual async Task Upload2Blob(long taskId, IStorageBlobManagement localChannel, string filePath, StorageBlob.CloudBlob blob) { string activity = String.Format(Resources.SendAzureBlobActivity, filePath, blob.Name, blob.Container.Name); string status = Resources.PrepareUploadingBlob; ProgressRecord pr = new ProgressRecord(OutputStream.GetProgressId(taskId), activity, status); DataMovementUserData data = new DataMovementUserData() { Data = blob, TaskId = taskId, Channel = localChannel, Record = pr }; TransferJob uploadJob = new TransferJob( new TransferLocation(filePath), new TransferLocation(blob), TransferMethod.SyncCopy); await this.RunTransferJob(uploadJob, data); if (this.BlobProperties != null || this.BlobMetadata != null) { await TaskEx.WhenAll( this.SetBlobProperties(localChannel, blob, this.BlobProperties), this.SetBlobMeta(localChannel, blob, this.BlobMetadata)); } try { await localChannel.FetchBlobAttributesAsync( blob, AccessCondition.GenerateEmptyCondition(), this.RequestOptions, this.OperationContext, this.CmdletCancellationToken); } catch (StorageException e) { //Handle the limited read permission. if (!e.IsNotFoundException()) { throw; } } WriteCloudBlobObject(data.TaskId, localChannel, blob); }
public async Task <bool> FireSpecialWeapon(CancellationToken cancellation) { if (SpecialAttack == null || SpecialWeaponAmmo.IsEmpty) { return(false); } SpecialWeaponAmmo.Quantity--; SoundManager.PlaySound("Special03"); await TaskEx.WhenAll( SpecialAttack(this), UpdateContext.Delay(SpecialWeaponDelay)); return(true); }
public async Task <IEnumerable <CallAggregationResult> > GetResultsAsync(IEnumerable <CallAggregationServiceDescription> services) { var requests = from s in services from c in s.Calls select new { Service = s, Call = c }; var tasks = requests.Select(p => CallServiceAsync(p.Service, p.Call)).ToList(); #if (!SILVERLIGHT && !NET4) await Task.WhenAll(tasks); #else await TaskEx.WhenAll(tasks); #endif return(tasks.Select(p => p.Result)); }
public async Task <IEnumerable <TvDbSeries> > GetSubscribedAsync(bool updateInBackground = true) { var subs = await subscribed; var loading = (from series in subs select UpdateSeriesIfNecessaryAsync(series)).ToArray(); if (updateInBackground) { return(subs); } await TaskEx.WhenAll(loading); return(subs); }
public Task Scan() { #if NET40 var task = TaskEx.Run(() => #else var task = Task.Run(() => #endif { this.Scanner.Scan(); }); #if NET40 return(TaskEx.WhenAll(task, this.Monitor(task))); #else return(Task.WhenAll(task, this.Monitor(task))); #endif }
private async void BeginAwaitForConsumtion() { while (true) { await _event; var tasks = new List <Task>(_bifferConsumersCount); for (int i = 0; i < _bifferConsumersCount; i++) { var task = TaskEx.Run(() => ConsumeAll()); tasks.Add(task); } await TaskEx.WhenAll(tasks); } }
public async Task FlushAsync() { this._flushCancellationTokenSource.Cancel(); bool lockTaken = false; WebCacheManager.CacheEntry[] cacheEntries; Dictionary <Uri, WebCacheManager.CacheEntry> dictionary; try { Monitor.Enter((object)(dictionary = this._cache), ref lockTaken); cacheEntries = Enumerable.ToArray <WebCacheManager.CacheEntry>((IEnumerable <WebCacheManager.CacheEntry>) this._cache.Values); this._cache.Clear(); } finally { if (lockTaken) { Monitor.Exit((object)dictionary); } } try { await TaskEx.WhenAll(Enumerable.Select <WebCacheManager.CacheEntry, Task>(Enumerable.Where <WebCacheManager.CacheEntry>((IEnumerable <WebCacheManager.CacheEntry>)cacheEntries, (Func <WebCacheManager.CacheEntry, bool>)(c => null != c.ReadTask)), (Func <WebCacheManager.CacheEntry, Task>)(c => c.ReadTask))).ConfigureAwait(false); } catch (OperationCanceledException ex) { } catch (Exception ex) { Debug.WriteLine("WebCacheManager.FlushAsync() exception: " + ExceptionExtensions.ExtendedMessage(ex)); } foreach (WebCacheManager.CacheEntry cacheEntry in cacheEntries) { cacheEntry.WebCache.WebReader.Dispose(); } bool flag; if (!flag) { ; } CancellationTokenSource fcts = this._flushCancellationTokenSource; this._flushCancellationTokenSource = new CancellationTokenSource(); fcts.Dispose(); }
async void Advertisements_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Reset) { foreach (var marker in MediaPlayer.Markers.Where(t => t.Type == MarkerType_Play || t.Type == MarkerType_Preload).ToList()) { MediaPlayer.Markers.Remove(marker); } foreach (var item in Advertisements.OfType <MidrollAdvertisement>()) { AddMarker(item); } } else { var tasks = new List <Task>(); if (e.OldItems != null) { foreach (var item in e.OldItems.OfType <MidrollAdvertisement>()) { var marker = MediaPlayer.Markers.FirstOrDefault(t => (t.Type == MarkerType_Play || t.Type == MarkerType_Preload) && t.Text == item.Id); if (marker != null) { MediaPlayer.Markers.Remove(marker); } if (activePreloadOperation != null && activePreloadOperation.AdSource == item.Source) { // no need to wait tasks.Add(activePreloadOperation.CancelAsync()); } } } if (e.NewItems != null) { foreach (var item in e.NewItems.OfType <MidrollAdvertisement>()) { AddMarker(item); } } #if SILVERLIGHT && !WINDOWS_PHONE || WINDOWS_PHONE7 await TaskEx.WhenAll(tasks); #else await Task.WhenAll(tasks); #endif } }
private async void RunBotThreadMethod() { //Create a task for each call var tasks = BuildTaskArray(); await TaskEx.WhenAll(tasks); if (Options.UsePersistentCache) { SaveCache(); } _uiDispatcher.BeginInvoke(new Action(() => { OnComplete?.Invoke(_filesToUpdate); })); }
private async void evaluate() { var geolocationAndIsp = GetGeolocationAndIsp(); foreach (var dataLists in await TaskEx.WhenAll(_servers.Select(ICMPTest))) { if (dataLists == null) { continue; } foreach (var dataList in dataLists.Where(dataList => dataList != null)) { await geolocationAndIsp; Append(dataList, geolocationAndIsp.Result); } } }
public async Task <List <Node> > Run_CoDong(int soLuong) { if (this.Graph == null || this.Graph.Count == 0 || this.Source == null) { throw new Exception("Cannot run Dijkstra without proper graph and source node."); } this.Initialize(); ChiaMang(soLuong); this.Source.Visited = true; this.visitedNodes = new List <Node>(); Node u = this.Source; while (visitedNodes.Count < this.Graph.Count) { u.Visited = true; this.visitedNodes.Add(u); var tasks = new List <Task <Node> >(); for (int dem = 0; dem < soLuong; dem++) { int index = dem; //if (dem == soLuong) //{ continue; } //else //{ var task1 = TaskEx.Run(() => PartialResult(mangs[index], u, visitedNodes)); tasks.Add(task1); //} } //tasks.Add(task2); var results = await TaskEx.WhenAll(tasks.ToArray()); Node min = new Node(); min.Distance = double.MaxValue; for (int i = 0; i < results.Length; i++) { if (min.Distance > results[i].Distance) { min = results[i]; } } u = min; } return(visitedNodes); }
public async Task SingletonReentrantTaskRespectsPriority() { var counter1 = 0; var counter2 = 0; var id = "5C8A060E-885C-4FF1-ABEB-DB046D2D8D1C"; var task1 = new SingletonReentrantTask(Placeholder.Instance, id, 10, SingletonReentrantTask.PRIORITY_LOW, async cancellationToken => { for (; counter1 + counter2 < 10; counter1++) { if (cancellationToken.IsCancellationRequested) { break; } #if NET40 await TaskEx.Delay(100).ConfigureAwait(false); #else await Task.Delay(100).ConfigureAwait(false); #endif } }); var task2 = new SingletonReentrantTask(Placeholder.Instance, id, 10, SingletonReentrantTask.PRIORITY_HIGH, async cancellationToken => { for (; counter1 + counter2 < 10; counter2++) { if (cancellationToken.IsCancellationRequested) { break; } #if NET40 await TaskEx.Delay(100).ConfigureAwait(false); #else await Task.Delay(100).ConfigureAwait(false); #endif } }); #if NET40 await TaskEx.WhenAll(task1.Run(), task2.Run()).ConfigureAwait(false); #else await Task.WhenAll(task1.Run(), task2.Run()).ConfigureAwait(false); #endif Assert.AreEqual(10, counter1 + counter2); Assert.Less(counter1, counter2); }