Project Name File Name Usage Source Code Link
Farleyfile InteractionResponse.cs Task.Factory.StartNew(() => GrabInner(text, whenDone, process, temp, changed)) Link To Source File
BudgetPlanner DownloadAndUpgradeViewModel.cs Task.Factory.StartNew(() => DownloadUpdate()) Link To Source File
BudgetPlanner ShellViewModel.cs Task.Factory.StartNew(() => { #if DEBUG if (Updater.CheckForNewVersion("http://budzet-domowy.pietkiewicz.pl/online-update-beta")) #else if (Updater.CheckForNewVersion(ConfigurationManager.GetValueOrDefault(ConfigurationKeys.UpdatePage, string.Empty))) #endif { ShowDialog(() => UpdateApplication(), () => CanCheckForUpdates = true); } else { if (showValidVersionMessage) { ShowMessage("Wersja aplikacji jest aktualna", () => _timer.Start()); CanCheckForUpdates = true; } else { _timer.Start(); } } }) Link To Source File
soundfingerprinting PathListViewModel.cs //count the number of available music files asynchronously Task.Factory.StartNew( () => { int count = Helper.CountNumberOfMusicFiles(selectedPath, _musicFileFilters, true); lock (LockObject) { int index = -1; foreach (Item path in Paths) { index++; if (path.Path == selectedPath) break; } if (Paths != null && Paths.Count >= index && index >= 0) { _totalMusicItems += count; Paths[index].Count = count; } } }) Link To Source File
soundfingerprinting PathListViewModel.cs Task.Factory.StartNew( () => { duplicates = _gate.FindAllDuplicates( (track, total, current) => { CurrentProgress = (int) Math.Ceiling(((float) (current)/total*100)); if (current >= total) { _processedMusicItems = current; /*set processed unit items*/ CurrentProgress = 0; } }); }) Link To Source File
soundfingerprinting ReportViewModel.cs Task.Factory.StartNew( () => { MoveDuplicatesToFolder(selectedPath); _isMoving = false; Process.Start("explorer.exe", selectedPath); }) Link To Source File
soundfingerprinting RepositoryGateway.cs Task.Factory.StartNew( () => { using (IAudio audioProxy = ServiceContainer.Kernel.Get()) { while (!bag.IsEmpty) { if (token.IsCancellationRequested) return; string file; if (!bag.TryTake(out file)) return; Track track; float[] samples; try { track = TrackHelper.GetTrackInfo(MIN_TRACK_LENGTH, MAX_TRACK_LENGTH, file, (BassProxy)audioProxy); //lame casting I know samples = TrackHelper.GetTrackSamples(track, audioProxy, SAMPLE_RATE, MILLISECONDS_TO_PROCESS, MILLISECONDS_START); } catch { continue; /*Continue processing even if getting samples failed*/ /*the failing might be caused by a bunch of File I/O factors, that cannot be considered critical*/ } try { buffer.TryAdd(new Tuple(track, samples), 1, token); /*producer*/ } catch (OperationCanceledException) { /*it is safe to break here, operation was canceled*/ break; } } } }, token) Link To Source File
Hermod TCPServer.cs Task.Factory.StartNew(() => { ProcessNewClientConnection(_NewTCPClient); }) Link To Source File
Hermod UDPServer.cs Task.Factory.StartNew(() => { // Create a local copy of the UDPPacket and RemoteEndPoint as we // do not want to wait till the new thread has accepted the packet //var _UDPPacketCopy = new Byte[_NumberOfReceivedBytes]; //Array.Copy(_UDPPacket, 0, _UDPPacketCopy, 0, _NumberOfReceivedBytes); //var _UDPPacketCopy = new Byte[_NumberOfReceivedBytes]; //Buffer.BlockCopy(_UDPPacket, 0, _UDPPacketCopy, 0, _NumberOfReceivedBytes); Array.Resize(ref _UDPPacket, _NumberOfReceivedBytes); var _UDPPacketCopy = _UDPPacket; var _RemoteSocket = new IPSocket((IPEndPoint) _RemoteEndPoint); _WaitForChildTask = false; ProcessNewPacket(_UDPPacketCopy, _RemoteSocket); }) Link To Source File
Illias UniqueTimestampTests.cs Task.Factory.StartNew(() => { Parallel.For(0, _NumberOfItems, i => { var _UniqueTS = new UniqueTimestamps(); _UniqueTS.ThreadId = Thread.CurrentThread.ManagedThreadId; _UniqueTS.Timestamp = UniqueTimestamp.Ticks; _ConcurrentBag.Add(_UniqueTS); }); }) Link To Source File
Illias UniqueTimestampTests.cs Task.Factory.StartNew(() => { Parallel.For(0, _NumberOfItems, j => { var _UniqueTS = new UniqueTimestamps(); _UniqueTS.ThreadId = Thread.CurrentThread.ManagedThreadId; _UniqueTS.Timestamp = UniqueTimestamp.Ticks; _ConcurrentBag.Add(_UniqueTS); }); }) Link To Source File
RunJS TimeoutHandler.cs Task.Factory.StartNew(() => { self.cancellationTokenSource.Token.ThrowIfCancellationRequested(); TimeSpan timeout = finnishTime - DateTime.Now; if (timeout < TimeSpan.Zero) timeout = TimeSpan.Zero; self.cancellationTokenSource.Token.WaitHandle.WaitOne(timeout); self.cancellationTokenSource.Token.ThrowIfCancellationRequested(); lock (self) { if (!self.timeouts.Contains(id)) return; self.timeouts.Remove(id); } self.scriptRunner.BeginInvoke(delegate { function.Call(self.Engine.Global); }); }, self.cancellationTokenSource.Token) Link To Source File
RunJS TimeoutHandler.cs Task.Factory.StartNew(() => { self.cancellationTokenSource.Token.ThrowIfCancellationRequested(); TimeSpan timeout = finnishTime - DateTime.Now; if (timeout < TimeSpan.Zero) timeout = TimeSpan.Zero; self.cancellationTokenSource.Token.WaitHandle.WaitOne(timeout); self.cancellationTokenSource.Token.ThrowIfCancellationRequested(); lock (self) { if (!self.intervals.Contains(id)) return; } self.scriptRunner.BeginInvoke(delegate { function.Call(self.Engine.Global); }); SetInterval(id, function, delay, finnishTime); }, self.cancellationTokenSource.Token) Link To Source File
RunJS JsRunnerTests.cs Task.Factory.StartNew(() => { Thread.Sleep(100); }) Link To Source File
AccelIRC Helper.cs System.Threading.Tasks.Task.Factory.StartNew(act) Link To Source File
MangaEplision Global.cs Task.Factory.StartNew(() => { BinaryFormatter binf = new BinaryFormatter(); LoadSource(); var fs = new FileStream(CatalogFilename, FileMode.Create); var dict = MangaSource.GetAvailableManga(); binf.Serialize(fs, dict); fs.Close(); fs.Dispose(); }) Link To Source File
MangaEplision SearchWindow.xaml.cs Task.Factory.StartNew(() => { info = Global.GetMangaInfo(name); }) Link To Source File
MangaEplision MainWindow.xaml.cs Task.Factory.StartNew(() => { #region System.Threading.Thread.Sleep(100); Global.Initialize(); Dispatcher.Invoke( new EmptyDelegate( () => { if (Global.Mangas != null) { CatalogListBox.ItemsSource = Global.Mangas; metroGroupBox1.NotificationsCount = Global.Mangas.Length; } #endregion })); }) Link To Source File
MangaEplision MainWindow.xaml.cs Task.Factory.StartNew(() => { if (Global.SavedQueue()) { Global.LoadQueue(ref DlQueue); Dispatcher.Invoke(new EmptyDelegate(() => { DlQueueList.ItemsSource = DlQueue; DlQueueList.Items.Refresh(); QueueStatuslbl.Content = string.Format("There are currently {0} items in your queue.", DlQueue.Count); if (DlQueue.Count > 0) CallStartQueueProcess(); })); Global.CleanupQueueDir(); } }) Link To Source File
MangaEplision MainWindow.xaml.cs Task.Factory.StartNew(() => { if (NetworkUtils.IsConnectedToInternet()) { foreach (BookEntry be in Global.MangaSource.GetNewReleasesOfToday(3)) { Dispatcher.BeginInvoke(new EmptyDelegate( () => { var bitmp = new BitmapImage(); bitmp.BeginInit(); bitmp.CacheOption = BitmapCacheOption.Default; bitmp.UriSource = new Uri(be.ParentManga.BookImageUrl); bitmp.EndInit(); //bitmp.Freeze(); var slide = new MetroBannerSlide(); slide.Header = be.Name + " / " + be.ParentManga.MangaName; slide.Image = bitmp; slide.FontSize = 25; slide.Foreground = Brushes.Red; slide.FontStyle = FontStyles.Oblique; metroBanner.Slides.Add(slide); })); } Dispatcher.BeginInvoke(new EmptyDelegate(() => { metroBanner.Slide = metroBanner.Slides[0]; metroBanner.Start(); LatestReleaseGB.NotificationsCount = metroBanner.Slides.Count; })); } }) Link To Source File
MangaEplision MainWindow.xaml.cs Task.Factory.StartNew(() => { info = Global.GetMangaInfo(name); }) Link To Source File
MangaEplision MainWindow.xaml.cs System.Threading.Tasks.Task.Factory.StartNew(() => { int i = 0; while (DlQueue.Count > 0) { isQueueRunning = true; QueueItem q = DlQueue[i]; if (Global.GetBookExist(q.Manga, q.Book)) return; else { q.Downloading = true; q.Status = QueueStatus.Downloading; Dispatcher.Invoke(new QueueUpDelegate((qi) => { QueueStatuslbl.Content = string.Format("Downloading {1}", DlQueue.Count, q.Name); DlQueueList.ItemsSource = DlQueue; DlQueueList.Items.Refresh(); }), q); Global.DownloadMangaBook(q.Manga, q.Book, (dlBook) => { q.Downloading = false; q.Status = QueueStatus.Completed; DlQueue.Remove(q); Dispatcher.Invoke(new EmptyDelegate(() => { DlQueueList.ItemsSource = DlQueue; DlQueueList.Items.Refresh(); QueueStatuslbl.Content = string.Format("Done! {0} items left in queue.", DlQueue.Count); Global.DisplayNotification(string.Format("{0} has downloaded.", q.Name), "Download Complete"); CurrProg.Value = 0; Count.Content = string.Format("{0}%", 0); Global.CollectionBooks.Add(dlBook); Global.BookCollection = Global.CollectionBooks; if (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor == 1) { //if Win7 this.TaskbarItemInfo.ProgressState = System.Windows.Shell.TaskbarItemProgressState.None; this.TaskbarItemInfo.ProgressValue = 0; } GlobalObjs.SoundManager.WindowsBalloon.Play(); })); }, (curr, total) => { Dispatcher.Invoke(new UpdateDelegate((cur, tot) => { int percent = ((((cur < tot) ? cur + 1 : cur) * 100) / tot); CurrProg.Value = percent; Count.Content = string.Format("{0}%", percent); if (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor == 1) { //if Win7 this.TaskbarItemInfo.ProgressState = System.Windows.Shell.TaskbarItemProgressState.Normal; this.TaskbarItemInfo.ProgressValue = (double)percent / 100; } }), curr, total); }); while (q.Downloading) System.Threading.Thread.Sleep(30000); } } QueueRunning = false; Global.DisplayNotification("Your queue has been emptied!", "Empty Queue!"); }) Link To Source File
wincat ProxyController.cs tf.StartNew(() => { lock (Connections) { Connections.Add( new ProxyConnection( serv.AcceptSocket(), Connections.Count) { Task = t }); } }) Link To Source File
wincat Helper.cs System.Threading.Tasks.Task.Factory.StartNew(act) Link To Source File
TrivialMongoMessageQueue TmMqReceiver.cs Task.Factory.StartNew( () => Receive( act ) ) Link To Source File
Web-Critters SimulationBase.cs Task.Factory.StartNew(() => ProcessLocation(location)) Link To Source File
Web-Critters WebCrittersForm.cs Task.Factory.StartNew(() => { for (int i = 0; i < generationCount; i++) { if (token.IsCancellationRequested) return; this.CasSimulation.RunGeneration(); } }) Link To Source File
siren LastFMUpdater.cs factory.StartNew(UpdateArtistInfo) Link To Source File
siren LastFMUpdater.cs factory.StartNew(UpdateUserPlays) Link To Source File
siren LastFMUpdater.cs factory.StartNew(UpdateArtistImages) Link To Source File
siren LastFMUpdater.cs factory.StartNew(UpdateAlbumArt) Link To Source File
SharpShare AfpTransport.cs Task.Factory.StartNew(() => { this.OnCommandReceived(header, payload); }) Link To Source File
Hex BoardCache.cs Task.Factory.StartNew(() => this.available.Add(new HexBoard(this.BoardSize))) Link To Source File
doc-db VowelCalc.cs Task.Factory.StartNew(() => { Parallel.ForEach(reduceSources, reduceItem => resultCollection.Add(reduce(reduceItem))); resultCollection.CompleteAdding(); }) Link To Source File
emitmapper-tools MapperTest.cs Task.Factory.StartNew(DataContainerToEntityMappingTest) Link To Source File
emitmapper-tools MapperTest.cs Task.Factory.StartNew(EntityToDataContainerMappingTest) Link To Source File
emitmapper-tools MapperTest.cs Task.Factory.StartNew(() => EntityToDataContainerMappingCollectionTest(numberOfThreads)) Link To Source File
emitmapper-tools MapperTest.cs Task.Factory.StartNew(() => DataContainerToEntityMappingCollectionTest(numberOfThreads)) Link To Source File
iocwrapper IoCConcurrencyTest.cs Task.Factory.StartNew(() => IoCContainer.Resolve()) Link To Source File
Xen-Game-Client Game.cs Task.Factory.StartNew(() => { // generate perlin 3d noise Vector3 noiseOffset = cellPos; noiseOffset.Y *= -1; cell.PerlinNoise(noiseOffset * terrainManager.cellDimensions.X, terrainNoiseDensity, seed); TerrainCellMesh mesh = new TerrainCellMesh(cell, cellPos, terrainManager.cellGap); mesh.Calculate(terrainManager.cubicTerrain); if (mesh == null) { throw new Exception("Problem generating mesh from volume!"); } // calculate convex hull mesh.CalculatePhysicsHull(); // add mesh's convex hull to the physics sim world.AddBody(mesh.RigidBody); lock (terrainLock) { terrainManager.terrainCellMeshes[(int)cellPos.X, (int)cellPos.Y, (int)cellPos.Z] = mesh; if (mesh.Vertices != null) terrainManager.vertexCount += mesh.Vertices.Count; terrainManager.cellsInitialized++; } //drawToRenderTarget.Add(new DrawRotated(terrainManager.terrainCellMeshes[(int)pos.X, (int)pos.Y, (int)pos.Z])); }) Link To Source File
rocketsockets ManagedSocketListener.cs Task.Factory.StartNew( ListenLoop ) Link To Source File
rocketsockets Win32SocketAdapter.cs Task.Factory.StartNew( Listen ) Link To Source File
Symbiote EventLoop.cs Task.Factory.StartNew( Loop ) Link To Source File
nCQRS ElementFetcher.cs Task.Factory.StartNew(() => Fetch(directive)) Link To Source File
nCQRS MsSqlServerEventStoreTests.cs Task.Factory.StartNew(() => { var changeEvent = new CustomerNameChanged(DateTime.Now.Ticks.ToString()) { CustomerId = theEventSourceId }; var eventStream = Prepare.Events(changeEvent) .ForSourceUncomitted(theEventSourceId, Guid.NewGuid(), 2); try { targetStore.Store(eventStream); } catch (ConcurrencyException) { concurrencyExceptionThrown = true; } targetStore.ReadFrom(theEventSourceId, long.MinValue, long.MaxValue); }) Link To Source File
nCQRS MsSqlServerEventStoreTests.cs Task.Factory.StartNew(() => { var theEventSourceId = Guid.NewGuid(); var theCommitId = Guid.NewGuid(); var eventStream = Prepare.Events(new CustomerCreatedEvent(Task.CurrentId.ToString(), 35)) .ForSourceUncomitted(theEventSourceId, theCommitId); // should not be receiving a deadlock targetStore.Store(eventStream); }) Link To Source File
Super2013 ElementFetcher.cs Task.Factory.StartNew(() => Fetch(directive)) Link To Source File
Super2013 MsSqlServerEventStoreTests.cs Task.Factory.StartNew(() => { var changeEvent = new CustomerNameChanged(DateTime.Now.Ticks.ToString()) { CustomerId = theEventSourceId }; var eventStream = Prepare.Events(changeEvent) .ForSourceUncomitted(theEventSourceId, Guid.NewGuid(), 2); try { targetStore.Store(eventStream); } catch (ConcurrencyException) { concurrencyExceptionThrown = true; } targetStore.ReadFrom(theEventSourceId, long.MinValue, long.MaxValue); }) Link To Source File
Super2013 MsSqlServerEventStoreTests.cs Task.Factory.StartNew(() => { var theEventSourceId = Guid.NewGuid(); var theCommitId = Guid.NewGuid(); var eventStream = Prepare.Events(new CustomerCreatedEvent(Task.CurrentId.ToString(), 35)) .ForSourceUncomitted(theEventSourceId, theCommitId); // should not be receiving a deadlock targetStore.Store(eventStream); }) Link To Source File
CouchDude CouchDBAzureBootstrapper.cs Task.Factory.StartNew( () => { // Preparing environment var logDir = new DirectoryInfo(logResource.RootPath); var binDir = new DirectoryInfo(binariesResource.RootPath); var getCouchDBDistributiveTask = GetFileTask.Start(tempDir, couchDBDistributive); var getCouchDBLuceneDistributiveTask = GetFileTask.Start(tempDir, couchDBLuceneDistributive); var getJreDistributiveTask = GetFileTask.Start(tempDir, jreDistributive); var getDataDirTask = useCloudDrive ? Task.Factory.StartNew(() => InitCloudDrive(cloudDriveSettings)) : Task.Factory.StartNew(() => new DirectoryInfo(dataResource.RootPath)); // Waiting for all prepare tasks to finish Task.WaitAll( getCouchDBDistributiveTask, getCouchDBLuceneDistributiveTask, getJreDistributiveTask, getDataDirTask); var bootstrapSettings = new BootstrapSettings { CouchDBDistributive = getCouchDBDistributiveTask.Result, CouchDBLuceneDistributive = getCouchDBLuceneDistributiveTask.Result, JavaDistributive = getJreDistributiveTask.Result, CouchDBLucenePort = localIPEndPoint.Port + 42, // hardcoded, but it's only matter within instance BinDirectory = binDir, DataDirectory = getDataDirTask.Result, LogDirectory = logDir, EndpointToListenOn = localIPEndPoint, SetupCouchDBLucene = true, // For some reason this is requried to run CouchDB in Azure or even devfabric UseShellExecute = true }; bootstrapSettings.ReplicationSettings.DatabasesToReplicate = databasesToReplicate; bootstrapSettings.ReplicationSettings.EndPointsToReplicateTo = endpointsToReplicateTo; return CouchDBBootstraper.Bootstrap(bootstrapSettings); }) Link To Source File
CouchDude GetFileTask.cs Task.Factory.StartNew( () => { var roleRootDirName = Environment.GetEnvironmentVariable("RoleRoot"); Debug.Assert(roleRootDirName != null); if (roleRootDirName.EndsWith(Path.VolumeSeparatorChar.ToString())) roleRootDirName += Path.DirectorySeparatorChar; var binDirectory = new DirectoryInfo( Path.Combine(roleRootDirName, "approot", "bin")); if (!binDirectory.Exists) // i.e. it's worker role, not web role binDirectory = new DirectoryInfo(Path.Combine(roleRootDirName, "approot")); var distributiveFile = new FileInfo( Path.Combine(binDirectory.FullName, distributiveNameOrUrl)); if (!distributiveFile.Exists) throw new Exception( String.Format( "Distributive file {0} have not been found. Check /"Copy to Output Directory/" property is set to /"Copy always/"", distributiveFile.FullName)); return distributiveFile; }) Link To Source File
CouchDude BootstrapperConsole.cs Task.Factory.StartNew( () => { System.Console.Write("Press ENTER to quit:"); System.Console.ReadLine(); foreach (var watchdog in watchdogs) watchdog.TerminateIfRunning(); shouldExit = true; }) Link To Source File
CouchDude CouchDBReplicator.cs Task.Factory.StartNew(() => { }) Link To Source File
CouchDude CouchSessionSaveChangesTests.cs Task.Factory.StartNew( () => { apiShouldEnter.WaitOne(); Interlocked.Increment(ref bulkUpdateCalled); updater(Mock.Of()); return returnInfo; }, TaskCreationOptions.PreferFairness ) Link To Source File
CouchDude CouchSessionSaveChangesTests.cs Task.Factory.StartNew( () => { saveChangesOperationStarted.Set(); saveChangesOperationShouldProceed.WaitOne(); updater(Mock.Of()); return returnInfo; } ) Link To Source File
CouchDude CouchSessionSaveChangesTests.cs Task.Factory.StartNew( () => { Task operation = null; switch (operationName) { case "load": operation = sesion.Load("doc1a"); break; case "query": operation = sesion.Query( new ViewQuery { DesignDocumentName = "dd1", ViewName = "byX", Key = "key1", IncludeDocs = true }); break; case "fullTextQuery": operation = sesion.QueryLucene( new LuceneQuery { DesignDocumentName = "dd1", IndexName = "byX", IncludeDocs = true, Query = "key1:2" }); break; } // ReSharper disable PossibleNullReferenceException operation.WaitOrThrowOnTimeout(); // ReSharper restore PossibleNullReferenceException }) Link To Source File
CouchDude ExceptionUtilsTests.cs Task.Factory .StartNew( () => { throw new InvalidOperationException("inner inner inner exception"); } ) Link To Source File
CouchDude TaskUtilsTasks.cs Task.Factory .StartNew( () => { throw new AggregateException( new AggregateException( new AggregateException( new Exception("one"), new Exception("two") ), new Exception("three"), new AggregateException( new AggregateException() ) ) ); }) Link To Source File
CouchDude TaskUtilsTasks.cs Task.Factory .StartNew( () => { throw new InvalidOperationException("inner inner inner exception"); } ) Link To Source File
CouchDude TaskUtilsTasks.cs Task.Factory .StartNew( () => { throw new InvalidOperationException("inner inner inner exception"); } ) Link To Source File
CouchDude ExploratoryTests.cs Task.Factory.StartNew( () => { Task.Factory .StartNew(() => Thread.Sleep(1000)) .ContinueWith( _ => { Thread.Sleep(1000); innerTaskContinuationFishTime = stopwatch.ElapsedTicks; }, TaskContinuationOptions.AttachedToParent); }) Link To Source File
CouchDude ExploratoryTests.cs Task.Factory .StartNew(() => Thread.Sleep(1000)) Link To Source File
starboard-sc2 BroadcasterPlugin.cs // The remaining work (format conversion, sending to xsplit) can be done on a seperate thread) Task.Factory.StartNew( () => { var encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bmp)); using (var stream = new MemoryStream()) { encoder.Save(stream); stream.Position = 0; byte[] bytes = stream.ToArray(); // Length of output data we're going to send. int length = width * height * 4; // Allocate memory for bitmap transfer to COM IntPtr dataptr = Marshal.AllocCoTaskMem(length); Marshal.Copy(bytes, bytes.Length - length, dataptr, length); this.xsplit.SendFrame((uint)width, (uint)height, dataptr.ToInt32()); // Send to broadcaster Marshal.FreeCoTaskMem(dataptr); } }) Link To Source File
AutoMapper MultiThreadingIssues.cs Task.Factory.StartNew( doMapping ) Link To Source File
NDistribUnit Client.cs Task.Factory.StartNew( () => { try { log.BeginActivity("Started running tests..."); TestResult tempResult; while ((tempResult = server.RunTests(testRun)) != null) { if (tempResult.IsFinal()) { result = tempResult; log.Info("Running all tests completed!"); break; } if (result == null) result = tempResult; else resultsProcessor.Merge(tempResult, result); SaveResult(result); PrintSummaryInfoForResult(tempResult); } log.EndActivity("Finished running tests"); } catch (Exception ex) { log.Error("An error occurred while running tests", ex); } }) Link To Source File
NDistribUnit Client.cs Task.Factory.StartNew( () => { try { log.BeginActivity("Checking for updates..."); var updatePackage = server.GetUpdatePackage( new UpdateRequest { Version = versionProvider.GetVersion() }); if (updatePackage.IsAvailable) { log.EndActivity("Update package available"); log.BeginActivity(string.Format("Receiving update to {0}...", updatePackage.Version)); updateReceiver.SaveUpdatePackage(updatePackage); log.EndActivity(string.Format("Update {0} was successfully received", updatePackage.Version)); } else log.EndActivity("No updates available."); } catch (Exception ex) { log.Warning("There was an exception when trying to get an update", ex); } }) Link To Source File
NDistribUnit CrossThreadPipe.cs Task.Factory.StartNew(action) Link To Source File
NDistribUnit CrossThreadPipe.cs Task.Factory.StartNew(closeAction) Link To Source File
NDistribUnit RunResultsCollection.cs Task.Factory.StartNew(PerformAsyncMerging) Link To Source File
NDistribUnit CrossThreadPipeTests.cs Task.Factory.StartNew(()=> { Thread.Sleep(50); pipe.Publish(2); }) Link To Source File
NDistribUnit CrossThreadPipeTests.cs Task.Factory.StartNew(()=> { Thread.Sleep(50); pipe.Close(); }) Link To Source File
NDistribUnit CrossThreadPipeTests.cs Task.Factory.StartNew(()=> { Thread.Sleep(50); pipe.Publish(6); }) Link To Source File
NDistribUnit CrossThreadPipeTests.cs Task.Factory.StartNew(()=> { Thread.Sleep(100); pipe.Close(); }) Link To Source File
NDistribUnit CrossThreadPipeTests.cs Task.Factory.StartNew(()=> { Thread.Sleep(50); pipe.Publish(6); }) Link To Source File
NDistribUnit CrossThreadPipeTests.cs Task.Factory.StartNew(()=> { Thread.Sleep(100); pipe.Close(); Thread.Sleep(20); pipe.Publish(7); }) Link To Source File
NDistribUnit CrossThreadPipeTests.cs Task.Factory.StartNew(()=> { Thread.Sleep(50); pipe.Publish(6); }) Link To Source File
NDistribUnit CrossThreadPipeTests.cs Task.Factory.StartNew(()=> { Thread.Sleep(100); pipe.Close(); Thread.Sleep(50); pipe.Publish(7); }) Link To Source File
NDistribUnit CrossThreadPipeTests.cs Task.Factory.StartNew( ()=> { pipe.Publish(2); pipe.Publish(4); pipe.Publish(8); pipe.Publish(16); }) Link To Source File
NDistribUnit CrossThreadPipeTests.cs Task.Factory.StartNew( ()=> { pipe.Publish(2); pipe.Publish(4); pipe.Publish(8); pipe.Publish(16); }) Link To Source File
NDistribUnit CrossThreadPipeTests.cs Task.Factory.StartNew(() => { Thread.Sleep(50); pipe.Publish(10); pipe.Close(); }) Link To Source File
Azyotter DirectMessagesReceiver.cs Task.Factory.StartNew(() => this.Query(TimelineItemCache.Instance) .ForEach(item => this.OnReceivedTimeline(new[] { item })) ) Link To Source File
Azyotter MentionsTimelineReceiver.cs Task.Factory.StartNew(() => this.Query(TimelineItemCache.Instance) .ForEach(status => this.OnReceivedTimeline(new[] { status })) ) Link To Source File
Azyotter UserStreamEventsReceiver.cs Task.Factory.StartNew(() => Query(TimelineItemCache.Instance) .ForEach(item => this.OnReceivedTimeline(new[] { item })) ) Link To Source File
Azyotter HomeTimelineReceiver.cs Task.Factory.StartNew(() => this.Query(TimelineItemCache.Instance) .ForEach(status => this.OnReceivedTimeline(new[] { status })) ) Link To Source File
Azyotter MainWindowViewModel.cs Task.Factory.StartNew(() => { if (Settings.Instance.AutoUpdate) new StatusBarViewModel(this.Messenger).CheckUpdate(true); else Update.GetCanUpdate(); }) Link To Source File
Azyotter ViewModel.cs Task.Factory.StartNew(() => { var disp = Application.Current.Dispatcher; string azyotterExePath; string packageId; Update targetUpdate; string tmpFile; try { azyotterExePath = Environment.GetCommandLineArgs()[1]; packageId = Environment.GetCommandLineArgs()[2]; if (!File.Exists(azyotterExePath)) throw new Exception(); } catch { this.Failed(disp, "引数が正しくないためアップデートを実行できませんでした。"); return; } DispatcherInvoke(disp, () => this.Message = "アップデート情報を取得しています..."); try { targetUpdate = Updates.GetUpdates().PackageId(packageId); } catch { this.Failed(disp, "アップデート情報の取得に失敗しました。"); return; } DispatcherInvoke(disp, () => this.Message = "ダウンロードしています..."); try { tmpFile = UpdateCore.Download(targetUpdate, percentage => DispatcherInvoke(disp, () => this.ProgressPercentage = percentage)); } catch { this.Failed(disp, "ダウンロードに失敗しました。"); return; } DispatcherInvoke(disp, () => { this.ProgressPercentage = 0; this.Message = "Azyotterの終了を待機しています..."; }); while (true) { var running = Process.GetProcesses() .Where(process => { try { return process.MainModule.FileName == azyotterExePath; } catch { return false; } }) .Any(); if (!running) break; Thread.Sleep(500); } DispatcherInvoke(disp, () => this.Message = "アップデートを適用しています..."); try { UpdateCore.Apply(tmpFile, Path.GetDirectoryName(azyotterExePath), percentage => DispatcherInvoke(disp, () => this.ProgressPercentage = percentage)); } catch { this.Failed(disp, "アップデートの適用に失敗しました。"); return; } finally { File.Delete(tmpFile); } DispatcherInvoke(disp, () => this.Message = "新しいAzyotterを起動しています..."); Process.Start(azyotterExePath, string.Format(@"""/u:{0}""", Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName))); ThreadPool.QueueUserWorkItem((state) => { Thread.Sleep(2000); disp.BeginInvoke(new Action(Application.Current.Shutdown)); }); }) Link To Source File
MsAccessRestrictor KeyboardHooking.cs Task.Factory.StartNew(ShowPasswordDialog) Link To Source File
practice MainWindow.xaml.cs Task.Factory.StartNew(() => { for (int i = 0; i < urlCount; i++) { var uri = new Uri(urls[i]); tasks[i] = Task.Factory.StartNew(() => this.SaveUri(uri, rootDirectory)).ContinueWith(t => this.DownloadProgressBar.Value += 1, uiSyncContext); } Task.WaitAll(tasks); }) Link To Source File
practice MainWindow.xaml.cs Task.Factory.StartNew(() => this.SaveUri(uri, rootDirectory)) Link To Source File
ByteLibrary Replay.cs Task.Factory.StartNew( () => { DateTime start = DateTime.Now; HttpStatusCode statusCode = this.GetResponseStatus(request); DateTime end = DateTime.Now; TimeSpan elapsed = end - start; this.processedCount++; if (Processed != null) { Processed(statusCode, elapsed, entry.Uri, this.processedCount); } }) Link To Source File
BCCL TaskFactoryHelper.cs UiTaskFactory.StartNew(action) Link To Source File
Terraria-Map-Editor WorldViewModel.cs Task.Factory.StartNew(() => { var w = nwDialog.NewWorld; w.SpawnX = w.TilesWide / 2; w.SpawnY = (int)Math.Max(0, w.GroundLevel - 10); w.GroundLevel = (int)w.GroundLevel; w.RockLevel = (int)w.RockLevel; w.BottomWorld = w.TilesHigh * 16; w.RightWorld = w.TilesWide * 16; w.Tiles = new Tile[w.TilesWide, w.TilesHigh]; Tile cloneTile = new Tile(); for (int y = 0; y < w.TilesHigh; y++) { OnProgressChanged(w, new ProgressChangedEventArgs(BCCL.Utility.Calc.ProgressPercentage(y, w.TilesHigh), "Generating World...")); if (y == (int)w.GroundLevel - 10) cloneTile = new Tile { HasWire = false, IsActive = true, IsLava = false, Liquid = 0, Type = 2, U = -1, V = -1, Wall = 2 }; if (y == (int)w.GroundLevel - 9) cloneTile = new Tile { HasWire = false, IsActive = true, IsLava = false, Liquid = 0, Type = 0, U = -1, V = -1, Wall = 2 }; else if (y == (int)w.GroundLevel + 1) cloneTile = new Tile { HasWire = false, IsActive = true, IsLava = false, Liquid = 0, Type = 0, U = -1, V = -1, Wall = 0 }; else if (y == (int)w.RockLevel) cloneTile = new Tile { HasWire = false, IsActive = true, IsLava = false, Liquid = 0, Type = 1, U = -1, V = -1, Wall = 0 }; else if (y == w.TilesHigh - 182) cloneTile = new Tile(); for (int x = 0; x < w.TilesWide; x++) { w.Tiles[x, y] = (Tile)cloneTile.Clone(); } } return w; }) Link To Source File
Terraria-Map-Editor WorldViewModel.cs Task.Factory.StartNew(() => CurrentWorld.Save(CurrentFile)) Link To Source File
Terraria-Map-Editor WorldViewModel.cs Task.Factory.StartNew(() => { try { return World.LoadWorld(filename); } catch (Exception e) { MessageBox.Show(e.Message); } return null; }) Link To Source File
Terraria-Map-Editor WorldViewModel.Editor.cs Task.Factory.StartNew( () => { if (CurrentWorld != null) { for (int y = 0; y < CurrentWorld.TilesHigh; y++) { Color curBgColor = GetBackgroundColor(y); OnProgressChanged(this, new ProgressChangedEventArgs(y.ProgressPercentage(CurrentWorld.TilesHigh), "Calculating Colors...")); for (int x = 0; x < CurrentWorld.TilesWide; x++) { PixelMap.SetPixelColor(x, y, Render.PixelMap.GetTileColor(CurrentWorld.Tiles[x, y], curBgColor, _showWalls, _showTiles, _showLiquid, _showWires)); } } } OnProgressChanged(this, new ProgressChangedEventArgs(0, "Render Complete")); }) Link To Source File
Terraria-Map-Editor WorldViewModel.Editor.cs Task.Factory.StartNew( () => { var bounded = new Rectangle(Math.Max(area.Left, 0), Math.Max(area.Top, 0), Math.Min(area.Width, CurrentWorld.TilesWide - Math.Max(area.Left, 0)), Math.Min(area.Height, CurrentWorld.TilesHigh - Math.Max(area.Top, 0))); if (CurrentWorld != null) { for (int y = bounded.Top; y < bounded.Bottom; y++) { Color curBgColor = GetBackgroundColor(y); OnProgressChanged(this, new ProgressChangedEventArgs(y.ProgressPercentage(CurrentWorld.TilesHigh), "Calculating Colors...")); for (int x = bounded.Left; x < bounded.Right; x++) { PixelMap.SetPixelColor(x, y, Render.PixelMap.GetTileColor(CurrentWorld.Tiles[x, y], curBgColor, _showWalls, _showTiles, _showLiquid, _showWires)); } } } OnProgressChanged(this, new ProgressChangedEventArgs(0, "Render Complete")); }) Link To Source File
Transvoxel-XNA MainForm.cs _uiFactory.StartNew(() => OnLogged(sender, e)) Link To Source File
Transvoxel-XNA MainForm.cs _uiFactory.StartNew(() => OnProgressChanged(sender, e)) Link To Source File
Transvoxel-XNA MainForm.cs Task.Factory.StartNew( () => { for (int i = 0; i <= sizex; i++) { _logger.Log("MAIN", i+"/"+sizex); OnProgressChanged(null, new ProgressChangedEventArgs((int)(((float)i/(float)sizex) * 100.0f), "Generating Volume Data...")); for (int j = 0; j <= sizey; j++) { for (int k = 0; k <= sizez; k++) { double div = 31.0; double val = (SimplexNoise.noise(i / div, j / div, k / div)) * 128.0; previewWindow1.TransvoxelManager.VolumeData[i,j,k] = (sbyte)val; } } //OnProgressChanged(null, new ProgressChangedEventArgs(100, "Generating Volume Data...")); } OnProgressChanged(null, new ProgressChangedEventArgs(0, string.Empty)); _logger.Log("MAIN", "Volume Data Generation Complete."); } ) Link To Source File
Transvoxel-XNA MainForm.cs Task.Factory.StartNew( () => { IVolumeData v = previewWindow1.TransvoxelManager.VolumeData; CompactOctree o = (CompactOctree)v; previewWindow1.TransvoxelManager.ExtractMesh(o.Head()); _logger.Log("MAIN", "Mesh Extraction Complete."); } ) Link To Source File
ExampleBox Bus.cs Task.Factory.StartNew(() => SendInternal(message)) Link To Source File
Test Connector_v1.cs Task.Factory.StartNew(delegate { Consument.Send(message); }) Link To Source File
Test Connector_v1.cs Task.Factory.StartNew(delegate { Consument.Send(message); }) Link To Source File
Test ManualMessageSender_v1.cs Task.Factory.StartNew(delegate { XDocument xmlDocument = XDocument.Parse(content); var message = new Message { RootElement = xmlDocument.Root }; MessageSent(message); }) Link To Source File
Test MesageFlowProcessor_v1.cs Task.Factory.StartNew(delegate { bool isHandled = HandleMessage(message, inputPoint); if (isHandled) { lock (inputPoint.MessagesLock){ inputPoint.Messages.Remove(message); } } }) Link To Source File
BTDB KeyValueDBTest.cs Task.Factory.StartNew(() => { var tr2 = tr2Task.Result; Assert.True(tr2.FindExactKey(_key1)); tr2.CreateKey(_key2); tr2.Commit(); tr2.Dispose(); }) Link To Source File
ILoveLucene ApplicationBootstrapper.cs Task.Factory.StartNew(ExecuteStartupTasks) Link To Source File
ILoveLucene MainWindowViewModel.cs Task.Factory.StartNew(() => { try { Status.SetMessage(this, "Executing"); IItem result = null; if (ActionWithArguments != null) { result = ActionWithArguments.ActOn(Result.Item, Arguments); } else { result = SelectedAction.ActOn(Result.Item); } _autoCompleteText.LearnInputForCommandResult(Input, Result); _getActionsForItem.LearnActionForCommandResult(Input, SelectedAction, Result); result = result ?? NoReturnValue.Object; if(result != NoReturnValue.Object) { _temporaryResults = result.ToListWithCurrentSelection(); UpdateCommandOptions(new ListWithCurrentSelection()); Input = CommandOptions.First().Item.Text; } else { Input = string.Empty; Arguments = string.Empty; // HACK _temporaryResults = new ListWithCurrentSelection(); Caliburn.Micro.Execute.OnUIThread(() => ((MainWindowView)Window.GetWindow(source)).HideWindow()); } Status.SetMessage(this, "Done"); } catch (Exception e) { Status.SetMessage(this, "Error :" + e.Message); Description = e.Message; _log.Error(e); } }) Link To Source File
ILoveLucene MainWindowViewModel.cs Task.Factory.StartNew(() => SetActionsForResult(Result)) Link To Source File
ILoveLucene MainWindowViewModel.cs Task.Factory.StartNew(() => SetActionsForResult(Result)) Link To Source File
ILoveLucene MainWindowViewModel.cs Task.Factory.StartNew(() => { var result = _autoCompleteText.Autocomplete(Input); token.ThrowIfCancellationRequested(); _log.Info("Got autocompletion '{0}' for '{1}' with {2} alternatives", result.AutoCompletedCommand, result.OriginalText, result.OtherOptions.Count()); ListWithCurrentSelection options; if (result.HasAutoCompletion) { options = new[] {result.AutoCompletedCommand} .Concat(result.OtherOptions) .ToListWithCurrentSelection(); } else { options = new TextItem(Input, Description).ToListWithCurrentSelection(); } UpdateCommandOptions(options); }, token) Link To Source File
ILoveLucene MainWindowViewModel.cs Task.Factory.StartNew(() => { var result = _autoCompleteText.Autocomplete(Input, true); token.ThrowIfCancellationRequested(); if (!result.HasAutoCompletion) return; var commandResults = new[] {result.AutoCompletedCommand} .Concat(result.OtherOptions).ToList(); Caliburn.Micro.Execute.OnUIThread( () => new ExplanationView(commandResults) .Show()); }, token) Link To Source File
ILoveLucene MainWindowViewModel.cs Task.Factory.StartNew(() => { var result = autoCompleteArgumentsCommand.AutoCompleteArguments(Item, Arguments); token.ThrowIfCancellationRequested(); _log.Info("Got autocompletion '{0}' for '{1}' with {2} alternatives", result.AutoCompletedArgument, result.OriginalText, result.OtherOptions.Count()); if (result.HasAutoCompletion) { ArgumentOptions = new[] {result.AutoCompletedArgument} .Concat(result.OtherOptions) .ToListWithCurrentSelection(); } else { ArgumentOptions = new ListWithCurrentSelection(Arguments); } Arguments = ArgumentOptions.Current; }, token) Link To Source File
babelim ChatViewModel.cs Task.Factory.StartNew ( () => { this.chat.SendMessage(message); } ) Link To Source File
babelim ChatViewModel.cs Task.Factory.StartNew ( () => { this.chat.SendChatStateNotification(notificationType); } ) Link To Source File
Castle.Transactions TransactionInterceptor.cs Task.Factory.StartNew(t => { var hasException = false; var tuple = (Tuple)t; var dependent = tuple.Item2.Transaction.Inner as DependentTransaction; using (tuple.Item2.GetForkScope()) try { if (_Logger.IsDebugEnabled) _Logger.DebugFormat("calling proceed on tx#{0}", tuple.Item3); using (var ts = new TransactionScope(dependent)) { tuple.Item1.Proceed(); if (_Logger.IsDebugEnabled) _Logger.DebugFormat("calling complete on TransactionScope for tx#{0}", tuple.Item3); ts.Complete(); } } catch (TransactionAbortedException ex) { // if we have aborted the transaction, we both warn and re-throw the exception hasException = true; if (_Logger.IsWarnEnabled) _Logger.Warn("transaction aborted", ex); throw new TransactionAbortedException( "Parallel/forked transaction aborted! See inner exception for details.", ex); } catch (Exception) { hasException = true; throw; } finally { if (_Logger.IsDebugEnabled) _Logger.Debug("in finally-clause, completing dependent if it didn't throw exception"); if (!hasException) dependent.Complete(); if (Finally != null) Finally.Set(); // See footnote at end of file } }, Tuple.Create(invocation, txData, txData.Transaction.LocalIdentifier)) Link To Source File
Castle.Windsor-READONLY ScopedLifestyleExplicitAndMultipleThreadsTestCase.cs Task.Factory.StartNew(() => { Assert.AreNotEqual(Thread.CurrentThread.ManagedThreadId, initialThreadId); instanceFromOtherThread = Container.Resolve(); }) Link To Source File
Windsor ScopedLifestyleExplicitAndMultipleThreadsTestCase.cs Task.Factory.StartNew(() => { Assert.AreNotEqual(Thread.CurrentThread.ManagedThreadId, initialThreadId); instanceFromOtherThread = Container.Resolve(); }) Link To Source File
sider ThreadPoolSample.cs Task.Factory.StartNew(() => { // obtain a key to increment string key; if (!keysBag.TryTake(out key)) WriteLine("ERROR"); // obtain an IRedisClient from the pool // and use it to INCR a key var client = pool.GetClient(); client.Incr(key); }) Link To Source File
sshnet ForwardedPortLocal.NET40.cs Task.Factory.StartNew(action) Link To Source File
sshnet ForwardedPortRemote.NET40.cs Task.Factory.StartNew(action) Link To Source File
sshnet KeyboardInteractiveConnectionInfo.NET40.cs Task.Factory.StartNew(action) Link To Source File
sshnet PasswordConnectionInfo.NET40.cs Task.Factory.StartNew(action) Link To Source File
sshnet SftpClient.NET40.cs Task.Factory.StartNew(action) Link To Source File
sshnet Shell.NET40.cs Task.Factory.StartNew(action) Link To Source File
sshnet SshCommand.NET40.cs Task.Factory.StartNew(action) Link To Source File
c-raft Client.cs Task.Factory.StartNew(Recv_Start) Link To Source File
c-raft Client.cs Task.Factory.StartNew(() => { foreach (Chunk chunk in _player.LoadedChunks.Values) { if (chunk != null) chunk.RemoveClient(this); } }) Link To Source File
c-raft Client.Recv.cs Task.Factory.StartNew(client.SendLoginSequence) Link To Source File
c-raft Server.cs Task.Factory.StartNew(DoPulse) Link To Source File
c-raft Server.cs Task.Factory.StartNew(FullSave) Link To Source File
c-raft Server.cs Task.Factory.StartNew(ProcessReadQueue) Link To Source File
c-raft Server.cs Task.Factory.StartNew(DisposeClients) Link To Source File
c-raft Server.cs Task.Factory.StartNew(ProcessSendQueue) Link To Source File
c-raft WorldManager.cs Task.Factory.StartNew(() => { Parallel.For(0, entry.Requests.Count, (i) => { ClientRequest req; if (!entry.Requests.TryDequeue(out req)) return; if (entry.ChunkRequested.LightToRecalculate) entry.ChunkRequested.RecalculateSky(); req.ClientRequesting.Owner.LoadedChunks.TryUpdate(entry.ChunkRequested.Coords.ChunkPackedCoords, entry.ChunkRequested, null); entry.ChunkRequested.AddClient(req.ClientRequesting); req.ClientRequesting.SendPreChunk(entry.ChunkRequested.Coords.ChunkX, entry.ChunkRequested.Coords.ChunkZ, true, false); req.ClientRequesting.SendChunk(entry.ChunkRequested, false); }); }) Link To Source File
c-raft WorldManager.cs // Triggered once every half second Task.Factory.StartNew(Server.DoPulse) Link To Source File
c-raft WorldManager.cs Task.Factory.StartNew(CollectProc) Link To Source File
c-raft WorldManager.cs Task.Factory.StartNew(GrowProc) Link To Source File
c-raft WorldManager.cs Task.Factory.StartNew(PhysicsProc) Link To Source File
c-raft WorldManager.cs Task.Factory.StartNew(EntityProc) Link To Source File
c-raft WorldManager.cs Task.Factory.StartNew(MobSpawnerProc) Link To Source File
c-raft MainService.cs Task.Factory.StartNew(RunServer) Link To Source File
c-raft ClientsLauncher.cs Task.Factory.StartNew(() => StartAndCreateClients(numClients)) Link To Source File
c-raft TestClient.cs Task.Factory.StartNew(RecvPacket) Link To Source File
c-raft TestClient.cs Task.Factory.StartNew(Send) Link To Source File
c-raft TestClient.cs Task.Factory.StartNew(Send) Link To Source File
coapp CleanerMain.cs Task.Factory.StartNew(Start) Link To Source File
coapp CleanerMainWindow.cs Task.Factory.StartNew(CleanerMain.Start) Link To Source File
coapp Logger.cs Task.Factory.StartNew(() => { while (!EventLog.SourceExists(Source)) { Thread.Sleep(20); } _ready = true; }) Link To Source File
coapp Logger.cs Task.Factory.StartNew(() => { for (var i = 0; i < 100 && !_ready; i++) { Thread.Sleep(50); } // go ahead and try, but don't whine if this gets dropped. try { _eventLog.WriteEntry(message, type, eventID, category, rawData); } catch { } }) Link To Source File
coapp SingleStep.cs Task.Factory.StartNew(() => { try { Logger.Warning("Started Toolkit Installer"); // Thread.Sleep(4000); NativeMethods.MsiSetInternalUI(2, IntPtr.Zero); NativeMethods.MsiSetExternalUI((context, messageType, message) => 1, 0x400, IntPtr.Zero); if (!Cancelling) { var file = MsiFilename; // if this is the CoApp MSI, we don't need to fetch the CoApp MSI. if (!IsCoAppToolkitMSI(MsiFilename)) { // get coapp.toolkit.msi file = AcquireFile("CoApp.Toolkit.msi", percentDownloaded => ActualPercent = percentDownloaded / 10); if (!IsCoAppToolkitMSI(file)) { MainWindow.Fail(LocalizedMessage.IDS_UNABLE_TO_ACQUIRE_COAPP_INSTALLER, "Unable to download the CoApp Installer MSI"); return; } } // We made it past downloading. ActualPercent = 10; // bail if someone has told us to. (good luck!) if (Cancelling) { return; } // get a reference to the delegate. uihandler = UiHandler; NativeMethods.MsiSetExternalUI(uihandler, 0x400, IntPtr.Zero); try { var CoAppCacheFolder = Path.Combine(CoAppRootFolder.Value, ".cache"); Directory.CreateDirectory(CoAppCacheFolder); var cachedPath = Path.Combine(CoAppCacheFolder, MsiCanonicalName + ".msi"); if (!File.Exists(cachedPath)) { File.Copy(file, cachedPath); } } catch (Exception e) { Logger.Error(e); } Logger.Warning("Running MSI"); // install CoApp.Toolkit msi. Don't blink, this can happen FAST! var result = NativeMethods.MsiInstallProduct(file, String.Format(@"TARGETDIR=""{0}/.installed/"" ALLUSERS=1 COAPP_INSTALLED=1 REBOOT=REALLYSUPPRESS", CoAppRootFolder.Value)); // set the ui hander back to nothing. NativeMethods.MsiSetExternalUI(null, 0x400, IntPtr.Zero); InstallTask = null; // after this point, all you can do is exit the installer. Logger.Warning("Done Installing MSI (rc={0}.",result); // did we succeed? if (result == 0) { ActualPercent = 80; // if the UI has not shown, it will try short circuit in the window constructor. // bail if someone has told us to. (good luck!) if (Cancelling) { return; } // we'll not be on the GUI thread when this runs. RunInstaller(false); } else { MainWindow.Fail(LocalizedMessage.IDS_CANT_CONTINUE, "Installation Engine failed to install. o_O"); } } } catch( Exception e ) { Logger.Error(e); MainWindow.Fail(LocalizedMessage.IDS_SOMETHING_ODD, "This can't be good."); } finally { InstallTask = null; } // if we got to this point, kinda feels like we should be failing }) Link To Source File
coapp MainWindow.xaml.cs Task.Factory.StartNew(() => { if (NativeResources.Value != null) { Dispatcher.Invoke((Action)delegate { containerPanel.Background.SetValue(ImageBrush.ImageSourceProperty, NativeResources.Value.GetBitmapImage(1201)); logoImage.SetValue(Image.SourceProperty, NativeResources.Value.GetBitmapImage(1202)); }); Logger.Warning("Loaded Resources."); } else { Logger.Warning("Unable to load resources Continuing anyway."); } }) Link To Source File
coapp AsyncConsoleProgram.cs Task.Factory.StartNew(() => { #if DEBUG new DebugMessage { WriteLine = (text) => { Console.WriteLine("[DEBUG][{0}] {1}", ++Counter,text); } }.Register(); #endif Main(args); }, CancellationTokenSource.Token) Link To Source File
coapp Logger.cs Task.Factory.StartNew(() => { while (!EventLog.SourceExists(Source)) { Thread.Sleep(20); } _ready = true; }) Link To Source File
coapp Logger.cs Task.Factory.StartNew(() => { for (var i = 0; i < 20 && !_ready; i++) { Thread.Sleep(10); } // go ahead and try, but don't whine if this gets dropped. try { _eventLog.WriteEntry(message, type, (short)pid, (short)category, rawData); } catch { } }) Link To Source File
coapp EnvironmentUtility.cs #if COAPP_ENGINE_CORE Rehash.ForceProcessToReloadEnvironment("explorer"); Rehash.ForceProcessToReloadEnvironment("services"); #else Task.Factory.StartNew(() => { User32.SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, "Environment", SMTO_ABORTIFHUNG, 1000, IntPtr.Zero); }) Link To Source File
coapp Downloader.cs Task.Factory.StartNew(() => { foreach (var location in locations) { try { var uri = new Uri(location); if (uri.IsFile) { // try to copy the file local. var remoteFile = uri.AbsoluteUri.CanonicalizePath(); // if this fails, we'll just move down the line. File.Copy(remoteFile, targetFilename); PackageManager.Instance.RecognizeFile(canonicalName, targetFilename, uri.AbsoluteUri, new PackageManagerMessages().Extend(messages)); return; } Task progressTask = null; var rf = RemoteFile.GetRemoteFile(uri, targetFilename); rf.Get(new RemoteFileMessages { Completed = (itemUri) => { PackageManager.Instance.RecognizeFile(canonicalName, targetFilename, uri.AbsoluteUri, new PackageManagerMessages().Extend(messages)); if( remoteFileMessages != null ) { remoteFileMessages.Completed(itemUri); } }, Failed = (itemUri) => { if (File.Exists(targetFilename)) { targetFilename.TryHardToDelete(); if( remoteFileMessages != null ) { remoteFileMessages.Failed(itemUri); } } }, Progress = (itemUri, percent) => { if (progressTask == null) { progressTask = PackageManager.Instance.DownloadProgress(canonicalName, percent); progressTask.ContinueWith((antecedent) => { progressTask = null; }); } if( remoteFileMessages != null ) { remoteFileMessages.Progress(itemUri, percent); } } }).Wait(); if (File.Exists(targetFilename)) { return; } } catch { // bogus, dude. // try the next one. } } PackageManager.Instance.UnableToAcquire(canonicalName, new PackageManagerMessages()); }, TaskCreationOptions.AttachedToParent) Link To Source File
coapp Installer.cs Task.Factory.StartNew(StartInstall) Link To Source File
coapp PackageManager.cs Task.Factory.StartNew(() => { EngineServiceManager.EnsureServiceIsResponding(); sessionId = sessionId ?? Process.GetCurrentProcess().Id.ToString(); for (int count = 0; count < 60; count++) { _pipe = new NamedPipeClientStream(".", "CoAppInstaller", PipeDirection.InOut, PipeOptions.Asynchronous, TokenImpersonationLevel.Impersonation); try { _pipe.Connect(500); _pipe.ReadMode = PipeTransmissionMode.Message; break; } catch { _pipe = null; } } if( _pipe == null ) { throw new CoAppException("Unable to connect to CoApp Service"); } StartSession(clientName, sessionId); try { while (IsConnected) { var incomingMessage = new byte[BufferSize]; var readTask = _pipe.ReadAsync(incomingMessage, 0, BufferSize); readTask.ContinueWith(antecedent => { if (antecedent.IsCanceled || antecedent.IsFaulted || !IsConnected) { Disconnect(); return; } var rawMessage = Encoding.UTF8.GetString(incomingMessage, 0, antecedent.Result); if (string.IsNullOrEmpty(rawMessage)) { return; } var responseMessage = new UrlEncodedMessage(rawMessage); int? rqid = responseMessage["rqid"]; Logger.Message("Response:{0}".format(responseMessage.ToSmallerString())); try { ManualEventQueue.GetQueue(rqid.GetValueOrDefault()).Enqueue(responseMessage); } catch { if (responseMessage.Command.Equals("session-started")) { if( Connected != null ) { Connected(); } return; } // Console.WriteLine("Unable to queue the response to the right request event queue!"); // Console.WriteLine(" Response:{0}", responseMessage.Command); // not able to queue up the response to the right task? } }).AutoManage(); readTask.Wait(); } } catch (Exception e) { Logger.Message("Connection Terminating with Exception {0}/{1}", e.GetType(), e.Message); } finally { Disconnect(); } }) Link To Source File
coapp PackageManager.cs Task.Factory.StartNew(Disconnected) Link To Source File
coapp PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("find-packages") { {"canonical-name", canonicalName}, {"name", name}, {"version", version}, {"arch", arch}, {"public-key-token", publicKeyToken}, {"dependencies", dependencies}, {"installed", installed}, {"active", active}, {"required", required}, {"blocked", blocked}, {"latest", latest}, {"index", index}, {"max-results", maxResults}, {"location", location}, {"force-scan", forceScan}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
coapp PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("get-package-details") { {"canonical-name", canonicalName}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
coapp PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("install-package") { {"canonical-name", canonicalName}, {"auto-upgrade", autoUpgrade}, {"force", force}, {"download", download}, {"pretend", pretend}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
coapp PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("find-feeds") { {"index", index}, {"max-results", maxResults}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
coapp PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("remove-feed") { {"location", location}, {"session", session}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
coapp PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("add-feed") { {"location", location}, {"session", session}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
coapp PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("verify-file-signature") { {"filename", filename}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
coapp PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("set-package") { {"canonical-name", canonicalName}, {"active", active}, {"required", required}, {"blocked", blocked}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
coapp PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("remove-package") { {"canonical-name", canonicalName}, {"force", force}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
coapp PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("unable-to-acquire") { {"canonical-name", canonicalName}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
coapp PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("download-progress") { {"canonical-name", canonicalName}, {"progress", progress.ToString()}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
coapp PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("recognize-file") { {"canonical-name", canonicalName}, {"local-location", localLocation}, {"remote-location", remoteLocation}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
coapp PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("suppress-feed") { {"location", location}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
coapp PackageManager.cs Task.Factory.StartNew(() => { using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("set-logging") { {"messages", Messages}, {"warnings", Warnings}, {"errors", Errors}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
coapp PackageManager.cs Task.Factory.StartNew( () => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("get-engine-status") { {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
coapp PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("get-policy") { {"name", policyName}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
coapp PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("add-to-policy") { {"name", policyName}, {"account", account}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
coapp PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("remove-from-policy") { {"name", policyName}, {"account", account}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
coapp PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("symlink") { {"existing-location", existingLocation}, {"new-link", newLink}, {"link-type", linkType.ToString()}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
coapp EngineService.cs // make sure coapp is properly set up. Task.Factory.StartNew(() => { try { Logger.Warning("Gonna make sure stuff is setup right."); // this ensures that composition rules are run for toolkit. Package.EnsureCanonicalFoldersArePresent(); Logger.Warning("Getting Version of CoApp."); var v = Package.GetCurrentPackageVersion("coapp.toolkit", "820d50196d4e8857"); Logger.Warning("CoApp Version : " + v); } catch (Exception e ) { Logger.Error(e); } }) Link To Source File
coapp EngineService.cs Task.Factory.StartNew(() => { try { Logger.Message("Service Restart Order Issued."); // make sure nobody else can connect. _instance.Value._cancellationTokenSource.Cancel(); // tell the clients to go away. Logger.Message("Telling clients to go away."); Session.NotifyClientsOfRestart(); Logger.Message("Waiting up to 30 seconds for clients to disconnect."); // I'll give you 30 seconds to get lost. for (var i = 0; i < 300 && Session.HasActiveSessions; i++) { Thread.Sleep(100); } if (Session.HasActiveSessions) { Logger.Message("Forcing Disconnection of clients."); Session.CancelAll(); } } catch(Exception e) { Logger.Error(e); } Logger.Message("Clients should be disconnected; forcing restart"); if (IsInteractive) { Process.Start(new ProcessStartInfo { FileName = Assembly.GetEntryAssembly().Location, Arguments = "--interactive" }); Environment.Exit(0); } else { Process.Start(new ProcessStartInfo { FileName = Assembly.GetEntryAssembly().Location, Arguments = "--restart" }); } }) Link To Source File
coapp NewPackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("find-package"); return; } if (!PackageManagerSession.Invoke.CheckForPermission(PermissionPolicy.EnumeratePackages)) { PackageManagerMessages.Invoke.PermissionRequired("EnumeratePackages"); return; } UpdateIsRequestedFlags(); // get basic list of packages based on primary characteristics if (!string.IsNullOrEmpty(canonicalName)) { // if canonical name is passed, override name,version,pkt,arch with the parsed canonicalname. var match = _canonicalNameParser.Match(canonicalName.ToLower()); if (!match.Success) { PackageManagerMessages.Invoke.Error("find-packages", "canonical-name", "Canonical name '{0}' does not appear to be a valid canonical name".format(canonicalName)); return; } name = match.Groups[1].Captures[0].Value; version = match.Groups[2].Captures[0].Value; arch = match.Groups[3].Captures[0].Value; publicKeyToken = match.Groups[4].Captures[0].Value; } if( forceScan == true ) { foreach( var feed in Feeds ) { feed.Stale = true; } } var results = SearchForPackages(name, version, arch, publicKeyToken, location); // filter results of list based on secondary filters results = from package in results where (installed == null || package.IsInstalled == installed) && (active == null || package.IsActive == active) && (required == null || package.IsRequired == required) && (blocked == null || package.IsBlocked == blocked) select package; // only the latest? if (latest == true) { results = results.HighestPackages(); } // if the client has asked for the dependencies as well, include them in the result set. // otherwise the client will get the names in if (dependencies == true) { // grab the dependencies too. var deps = results.SelectMany(each => each.InternalPackageData.Dependencies).Distinct(); if (latest == true) { deps = deps.HighestPackages(); } results = results.Union(deps).Distinct(); } // paginate the results if (index.HasValue) { results = results.Skip(index.Value); } if (maxResults.HasValue) { results = results.Take(maxResults.Value); } if (results.Any()) { foreach (var package in results) { if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("find-packages"); return; } // otherwise, we're installing a dependency, and we need something compatable. var supercedents = (from p in SearchForPackages(package.Name, null, package.Architecture, package.PublicKeyToken) where p.InternalPackageData.PolicyMinimumVersion <= package.Version && p.InternalPackageData.PolicyMaximumVersion >= package.Version select p).OrderByDescending(p => p.Version).ToArray(); PackageManagerMessages.Invoke.PackageInformation(package, supercedents); } } else { PackageManagerMessages.Invoke.NoPackagesFound(); } }, TaskCreationOptions.AttachedToParent) Link To Source File
coapp NewPackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("get-package-details"); return; } var package = GetSinglePackage(canonicalName, "get-package-details"); if (package == null) { return; } PackageManagerMessages.Invoke.PackageDetails(package); }, TaskCreationOptions.AttachedToParent) Link To Source File
coapp NewPackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("install-package"); return; } var overallProgress = 0.0; var eachTaskIsWorth = 0.0; var numberOfPackagesToInstall = 0; var numberOfPackagesToDownload = 0; using (var manualResetEvent = new ManualResetEvent(true)) { try { lock (manualResetEvents) { manualResetEvents.Add(manualResetEvent); } var packagesTriedToDownloadThisTask = new List(); var package = GetSinglePackage(canonicalName, "install-package"); if (package == null) { PackageManagerMessages.Invoke.UnknownPackage(canonicalName); return; } // is the user authorized to install this? var highestInstalledPackage = SearchForInstalledPackages(package.Name, null, package.Architecture, package.PublicKeyToken).HighestPackages(); if (highestInstalledPackage.Any() && highestInstalledPackage.FirstOrDefault().Version < package.Version) { if (package.IsBlocked) { PackageManagerMessages.Invoke.PackageBlocked(canonicalName); return; } if (!PackageManagerSession.Invoke.CheckForPermission(PermissionPolicy.UpdatePackage)) { PackageManagerMessages.Invoke.PermissionRequired("UpdatePackage"); return; } } else { if (!PackageManagerSession.Invoke.CheckForPermission(PermissionPolicy.InstallPackage)) { PackageManagerMessages.Invoke.PermissionRequired("InstallPackage"); return; } } // mark the package as the client requested. package.PackageSessionData.DoNotSupercede = (false == autoUpgrade); package.PackageSessionData.UpgradeAsNeeded = (true == autoUpgrade); package.PackageSessionData.IsClientSpecified = true; // the resolve-acquire-install-loop do { // if the world changes, this will get set somewhere between here and the // other end of the do-loop. manualResetEvent.Reset(); if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("install-package"); return; } IEnumerable installGraph = null; try { installGraph = GenerateInstallGraph(package).ToArray(); } catch (OperationCompletedBeforeResultException) { // we encountered an unresolvable condition in the install graph. // messages should have already been sent. PackageManagerMessages.Invoke.FailedPackageInstall(canonicalName, package.InternalPackageData.LocalLocation, "One or more dependencies are unable to be resolved."); return; } // seems like a good time to check if we're supposed to bail... if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("install-package"); return; } if (download == false && pretend == true) { // we can just return a bunch of foundpackage messages, since we're not going to be // actually installing anything, nor trying to download anything. foreach( var p in installGraph) { PackageManagerMessages.Invoke.PackageInformation(package, Enumerable.Empty()); } return; } // we've got an install graph. // let's see if we've got all the files var missingFiles = from p in installGraph where !p.InternalPackageData.HasLocalLocation select p; if( download == true ) { // we want to try downloading all the files that we're missing, regardless if we've tried before. // unless we've already tried in this task once. foreach( var p in missingFiles.Where( each => packagesTriedToDownloadThisTask.Contains(each)) ) { packagesTriedToDownloadThisTask.Add(p); p.PackageSessionData.CouldNotDownload = false; } } if( numberOfPackagesToInstall != installGraph.Count() || numberOfPackagesToDownload != missingFiles.Count() ) { // recalculate the rest of the install progress based on the new install graph. numberOfPackagesToInstall = installGraph.Count(); numberOfPackagesToDownload = missingFiles.Count(); eachTaskIsWorth = (1.0 - overallProgress)/(numberOfPackagesToInstall + numberOfPackagesToDownload); } if (missingFiles.Any()) { // we've got some packages to install that don't have files. foreach (var p in missingFiles.Where(p => !p.PackageSessionData.HasRequestedDownload)) { PackageManagerMessages.Invoke.RequireRemoteFile(p.CanonicalName, p.InternalPackageData.RemoteLocations , PackageManagerSettings.CoAppCacheDirectory, false); p.PackageSessionData.HasRequestedDownload = true; } } else { if( pretend == true ) { // we can just return a bunch of found-package messages, since we're not going to be // actually installing anything, and everything we needed is downloaded. foreach (var p in installGraph) { PackageManagerMessages.Invoke.PackageInformation(p, Enumerable.Empty()); } return; } var failed = false; // no missing files? Check // complete install graph? Check foreach (var p in installGraph) { var pkg = p; // seems like a good time to check if we're supposed to bail... if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("install-package"); return; } var validLocation = package.PackageSessionData.LocalValidatedLocation; try { if (!pkg.IsInstalled) { if (string.IsNullOrEmpty(validLocation)) { // can't find a valid location PackageManagerMessages.Invoke.FailedPackageInstall(pkg.CanonicalName, pkg.InternalPackageData.LocalLocation, "Can not find local valid package"); pkg.PackageSessionData.PackageFailedInstall = true; } else { var lastProgress = 0; // GS01: We should put a softer lock here to keep the client aware that packages // are being installed on other threads... lock (typeof (MSIBase)) { if (EngineService.DoesTheServiceNeedARestart) { // something has changed where we need restart the service before we can continue. // and the one place we don't wanna be when we issue a shutdown in in Install :) ... EngineService.RestartService(); PackageManagerMessages.Invoke.OperationCancelled("install-package"); return; } pkg.Install(percentage => { overallProgress += ((percentage - lastProgress) *eachTaskIsWorth)/100; lastProgress = percentage; PackageManagerMessages.Invoke.InstallingPackageProgress(pkg.CanonicalName, percentage, (int)(overallProgress*100)); }); } overallProgress += ((100 - lastProgress)*eachTaskIsWorth)/100; PackageManagerMessages.Invoke.InstallingPackageProgress(pkg.CanonicalName, 100,(int)(overallProgress*100)); PackageManagerMessages.Invoke.InstalledPackage(pkg.CanonicalName); } } } catch (Exception e ) /* (PackageInstallFailedException pife) */ { Logger.Error("FAILED INSTALL"); Logger.Error(e); PackageManagerMessages.Invoke.FailedPackageInstall(pkg.CanonicalName, validLocation, "Package failed to install."); pkg.PackageSessionData.PackageFailedInstall = true; if (!pkg.PackageSessionData.AllowedToSupercede) { throw new OperationCompletedBeforeResultException(); // user specified packge as critical. } failed = true; break; } } if (!failed) { // W00T ... We did it! // check for restart required... if (EngineService.DoesTheServiceNeedARestart) { // something has changed where we need restart the service before we can continue. // and the one place we don't wanna be when we issue a shutdown in in Install :) ... EngineService.RestartService(); PackageManagerMessages.Invoke.OperationCancelled("install-package"); return; } return; } // otherwise, let's run it thru again. maybe it'll come together. } //---------------------------------------------------------------------------- // wait until either the manualResetEvent is set, but check every second or so // to see if the client has cancelled the operation. while (!manualResetEvent.WaitOne(500)) { if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("install-package"); return; } // we can also use this opportunity to update progress on any outstanding download tasks. overallProgress += missingFiles.Sum(missingFile => ((missingFile.PackageSessionData.DownloadProgressDelta*eachTaskIsWorth)/100)); } } while (true); } catch (OperationCompletedBeforeResultException) { // can't continue with options given. return; } finally { // remove manualResetEvent from the mre list lock (manualResetEvents) { manualResetEvents.Remove(manualResetEvent); } } } }, TaskCreationOptions.AttachedToParent) Link To Source File
coapp NewPackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } try { // it takes a non-trivial amount of time to lookup a package by its name. // so, we're going to cache the package in the session. // of course if there isn't one, (because we're downloading soemthing we don't know what it's actualy canonical name is) // we don't want to try looking up each time again, since that's the worst-case-scenario, we have to // cache the fact that we have cached nothing. // /facepalm. Package package; var cachedPackageName = SessionCache.Value["cached-the-lookup" + canonicalName]; if( cachedPackageName == null ) { SessionCache.Value["cached-the-lookup" + canonicalName] = "yes"; package = GetSinglePackage(canonicalName, "download-progress", true); if (package != null) { SessionCache.Value[canonicalName] = package; } } else { package = SessionCache.Value[ canonicalName]; } if (package != null) { package.PackageSessionData.DownloadProgress = Math.Max(package.PackageSessionData.DownloadProgress, downloadProgress.GetValueOrDefault()); } } catch { // suppress any exceptions... we just don't care! } SessionCache.Value["busy" + canonicalName] = null; }, TaskCreationOptions.AttachedToParent) Link To Source File
coapp NewPackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("list-feeds"); return; } var canFilterSession = PackageManagerSession.Invoke.CheckForPermission(PermissionPolicy.EditSessionFeeds); var canFilterSystem = PackageManagerSession.Invoke.CheckForPermission(PermissionPolicy.EditSystemFeeds); var activeSessionFeeds = SessionCache.Value.SessionValues; var activeSystemFeeds = Cache.Value.Values; var x = from feedLocation in SystemFeedLocations let theFeed = activeSystemFeeds.Where(each => each.IsLocationMatch(feedLocation)).FirstOrDefault() let validated = theFeed != null select new { feed = feedLocation, LastScanned = validated ? theFeed.LastScanned : DateTime.FromFileTime(0), session = false, suppressed = canFilterSystem && BlockedScanLocations.Contains(feedLocation), validated, }; var y = from feedLocation in SessionFeedLocations let theFeed = activeSessionFeeds.Where(each => each.IsLocationMatch(feedLocation)).FirstOrDefault() let validated = theFeed != null select new { feed = feedLocation, LastScanned = validated ? theFeed.LastScanned : DateTime.FromFileTime(0), session = true, suppressed = canFilterSession && BlockedScanLocations.Contains(feedLocation), validated, }; var results = x.Union(y); // paginate the results if (index.HasValue) { results = results.Skip(index.Value); } if (maxResults.HasValue) { results = results.Take(maxResults.Value); } if (results.Any()) { foreach (var f in results) { PackageManagerMessages.Invoke.FeedDetails(f.feed, f.LastScanned, f.session, f.suppressed, f.validated); } } else { PackageManagerMessages.Invoke.NoFeedsFound(); } }, TaskCreationOptions.AttachedToParent) Link To Source File
coapp NewPackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("add-feed"); return; } if (session ?? false) { // new feed is a session feed // session feed specfied if (!PackageManagerSession.Invoke.CheckForPermission(PermissionPolicy.EditSessionFeeds)) { PackageManagerMessages.Invoke.PermissionRequired("EditSessionFeeds"); return; } // check if it is already a system feed if (SystemFeedLocations.Contains(location)) { PackageManagerMessages.Invoke.Warning("add-feed", "location", "location '{0}' is already a system feed".format(location)); return; } if (SessionFeedLocations.Contains(location)) { PackageManagerMessages.Invoke.Warning("add-feed", "location", "location '{0}' is already a session feed".format(location)); return; } AddSessionFeed(location); PackageManagerMessages.Invoke.FeedAdded(location); // add feed to the session feeds. PackageFeed.GetPackageFeedFromLocation(location).ContinueWith(antecedent => { var foundFeed = antecedent.Result; if (foundFeed != null) { if (foundFeed != SessionPackageFeed.Instance || foundFeed != InstalledPackageFeed.Instance ) { SessionCache.Value[location] = foundFeed; } } else { PackageManagerMessages.Invoke.Error("add-feed", "location", "failed to recognize location '{0}' as a valid package feed".format(location)); LogMessage("Feed {0} was unable to load.", location); } }, TaskContinuationOptions.AttachedToParent); } else { // new feed is a system feed if (!PackageManagerSession.Invoke.CheckForPermission(PermissionPolicy.EditSystemFeeds)) { PackageManagerMessages.Invoke.PermissionRequired("EditSystemFeeds"); return; } if (SystemFeedLocations.Contains(location)) { PackageManagerMessages.Invoke.Warning("add-feed", "location", "location '{0}' is already a system feed".format(location)); return; } AddSystemFeed(location); PackageManagerMessages.Invoke.FeedAdded(location); // add feed to the system feeds. PackageFeed.GetPackageFeedFromLocation(location).ContinueWith(antecedent => { var foundFeed = antecedent.Result; if (foundFeed != null) { if (foundFeed != SessionPackageFeed.Instance || foundFeed != InstalledPackageFeed.Instance) { Cache.Value[location] = foundFeed; } } else { PackageManagerMessages.Invoke.Error("add-feed", "location", "failed to recognize location '{0}' as a valid package feed".format(location)); LogMessage("Feed {0} was unable to load.", location); } }, TaskContinuationOptions.AttachedToParent); } }, TaskCreationOptions.AttachedToParent) Link To Source File
coapp NewPackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("verify-signature"); return; } if (string.IsNullOrEmpty(filename)) { PackageManagerMessages.Invoke.Error("verify-signature", "filename", "parameter 'filename' is required to verify a file"); return; } var location = PackageManagerSession.Invoke.GetCanonicalizedPath(filename); if (!File.Exists(location)) { PackageManagerMessages.Invoke.FileNotFound(location); return; } var r = Verifier.HasValidSignature(location); if (r) { PackageManagerMessages.Invoke.SignatureValidation(location, r, Verifier.GetPublisherInformation(location)["PublisherName"]); } else { PackageManagerMessages.Invoke.SignatureValidation(location, false, null); } }, TaskCreationOptions.AttachedToParent) Link To Source File
coapp NewPackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("set-package"); return; } var package = GetSinglePackage(canonicalName, "set-package"); if (package == null) { PackageManagerMessages.Invoke.UnknownPackage(canonicalName); return; } if (!package.IsInstalled) { PackageManagerMessages.Invoke.Error("set-package", "canonical-name", "package '{0}' is not installed.".format(canonicalName)); return; } // seems like a good time to check if we're supposed to bail... if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("set-package"); return; } if (true == active) { if (!PackageManagerSession.Invoke.CheckForPermission(PermissionPolicy.ChangeActivePackage)) { PackageManagerMessages.Invoke.PermissionRequired("ChangeActivePackage"); } else { package.SetPackageCurrent(); } } if (false == active) { if (!PackageManagerSession.Invoke.CheckForPermission(PermissionPolicy.ChangeActivePackage)) { PackageManagerMessages.Invoke.PermissionRequired("ChangeActivePackage"); } else { SearchForInstalledPackages(package.Name, null, package.Architecture, package.PublicKeyToken).HighestPackages().FirstOrDefault(). SetPackageCurrent(); } } if (true == required) { if (!PackageManagerSession.Invoke.CheckForPermission(PermissionPolicy.ChangeRequiredState)) { PackageManagerMessages.Invoke.PermissionRequired("ChangeRequiredState"); } else { package.IsRequired = true; } } if (false == required) { if (!PackageManagerSession.Invoke.CheckForPermission(PermissionPolicy.ChangeRequiredState)) { PackageManagerMessages.Invoke.PermissionRequired("ChangeRequiredState"); } else { package.IsRequired = false; } } if (true == blocked) { if (!PackageManagerSession.Invoke.CheckForPermission(PermissionPolicy.ChangeBlockedState)) { PackageManagerMessages.Invoke.PermissionRequired("ChangeBlockedState"); } else { package.IsBlocked = true; } } if (false == blocked) { if (!PackageManagerSession.Invoke.CheckForPermission(PermissionPolicy.ChangeBlockedState)) { PackageManagerMessages.Invoke.PermissionRequired("ChangeBlockedState"); } else { package.IsBlocked = false; } } PackageManagerMessages.Invoke.PackageInformation(package, Enumerable.Empty()); }, TaskCreationOptions.AttachedToParent) Link To Source File
coapp NewPackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("remove-package"); return; } if (!PackageManagerSession.Invoke.CheckForPermission(PermissionPolicy.RemovePackage)) { PackageManagerMessages.Invoke.PermissionRequired("RemovePackage"); return; } var package = GetSinglePackage(canonicalName, "remove-package"); if (package == null) { PackageManagerMessages.Invoke.UnknownPackage(canonicalName); return; } if (package.Name.Equals( "coapp.toolkit", StringComparison.CurrentCultureIgnoreCase ) && package.PublicKeyToken.Equals("820d50196d4e8857") && package.IsActive ) { PackageManagerMessages.Invoke.Error("remove-package", "canonical-name", "Active CoApp Engine may not be removed"); return; } if (!package.IsInstalled) { PackageManagerMessages.Invoke.Error("remove-package", "canonical-name", "package '{0}' is not installed.".format(canonicalName)); return; } if (package.IsBlocked) { PackageManagerMessages.Invoke.PackageBlocked(canonicalName); return; } if (true != force) { UpdateIsRequestedFlags(); if (package.PackageSessionData.IsDependency) { PackageManagerMessages.Invoke.FailedPackageRemoval(canonicalName, "Package '{0}' is a required dependency of another package.".format(canonicalName)); return; } } // seems like a good time to check if we're supposed to bail... if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("remove-package"); return; } try { package.Remove((percentage) => PackageManagerMessages.Invoke.RemovingPackageProgress(package.CanonicalName, percentage)); PackageManagerMessages.Invoke.RemovingPackageProgress(canonicalName, 100); PackageManagerMessages.Invoke.RemovedPackage(canonicalName); } catch (OperationCompletedBeforeResultException e) { PackageManagerMessages.Invoke.FailedPackageRemoval(canonicalName, e.Message); return; } }, TaskCreationOptions.AttachedToParent) Link To Source File
coapp NewPackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("unable-to-acquire"); return; } if (canonicalName.IsNullOrEmpty()) { PackageManagerMessages.Invoke.Error("unable-to-acquire", "canonical-name", "canonical-name is required."); return; } // if there is a continuation task for the canonical name that goes along with this, // we should continue with that task, and get the heck out of here. // var package = GetSinglePackage(canonicalName, null); if (package != null) { package.PackageSessionData.CouldNotDownload = true; } var continuationTask = SessionCache>.Value[canonicalName]; SessionCache>.Value.Clear(canonicalName); Updated(); // notify threads that we're not going to be able to get that file. if (continuationTask != null) { var state = continuationTask.AsyncState as RequestRemoteFileState; if (state != null) { state.LocalLocation = null; } // the task can run, continuationTask.Start(); return; } }, TaskCreationOptions.AttachedToParent) Link To Source File
coapp NewPackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } if (string.IsNullOrEmpty(localLocation)) { PackageManagerMessages.Invoke.Error("recognize-file", "local-location", "parameter 'local-location' is required to recognize a file"); return; } if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("recognize-file"); return; } var location = PackageManagerSession.Invoke.GetCanonicalizedPath(localLocation); if (location.StartsWith(@"//")) { // a local unc path was passed. This isn't allowed--we need a file on a local volume that // the user has access to. PackageManagerMessages.Invoke.Error("recognize-file", "local-location", "local-location '{0}' appears to be a file on a remote server('{1}') . Recognized files must be local".format(localLocation, location)); return; } if (!File.Exists(location)) { PackageManagerMessages.Invoke.FileNotFound(location); return; } // if there is a continuation task for the canonical name that goes along with this, // we should continue with that task, and get the heck out of here. // if (!canonicalName.IsNullOrEmpty()) { var continuationTask = SessionCache>.Value[canonicalName]; SessionCache>.Value.Clear(canonicalName); if (continuationTask != null) { var state = continuationTask.AsyncState as RequestRemoteFileState; if (state != null) { state.LocalLocation = localLocation; } continuationTask.Start(); return; } } // otherwise, we'll call the recognizer Recognizer.Recognize(location).ContinueWith(antecedent => { if (antecedent.IsFaulted) { PackageManagerMessages.Invoke.FileNotRecognized(location, "Unexpected error recognizing file."); return; } if (antecedent.Result.IsPackageFile) { var package = Package.GetPackageFromFilename(location); // mark it download 100% package.PackageSessionData.DownloadProgress = 100; SessionPackageFeed.Instance.Add(package); PackageManagerMessages.Invoke.PackageInformation(package, Enumerable.Empty()); PackageManagerMessages.Invoke.Recognized(localLocation); return; } if (antecedent.Result.IsPackageFeed) { PackageManagerMessages.Invoke.FeedAdded(location); PackageManagerMessages.Invoke.Recognized(location); } // if this isn't a package file, then there is something odd going on here. // we don't accept non-package files willy-nilly. PackageManagerMessages.Invoke.FileNotRecognized(location, "File isn't a package, and doesn't appear to have been requested. "); return; }, TaskContinuationOptions.AttachedToParent); }, TaskCreationOptions.AttachedToParent) Link To Source File
coapp NewPackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("suppress-feed"); return; } var suppressedFeeds = SessionCache>.Value["suppressed-feeds"] ?? new List(); lock (suppressedFeeds) { if (!suppressedFeeds.Contains(location)) { suppressedFeeds.Add(location); SessionCache>.Value["suppressed-feeds"] = suppressedFeeds; } } PackageManagerMessages.Invoke.FeedSuppressed(location); }, TaskCreationOptions.AttachedToParent) Link To Source File
coapp PackageCollectionExtensions.cs Task.Factory.StartNew(() => { }) Link To Source File
coapp Session.cs Task.Factory.StartNew(() => { new PackageManagerMessages { RequestId = requestMessage["rqid"], }.Extend(_messages).Register(); var policyName = requestMessage["name"].ToString(); var policy = PermissionPolicy.AllPolicies.Where(each => each.Name.Equals(policyName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault(); if( policy == null ) { SendMessageArgumentError("get-policy", "name", "policy '{0}' not found".format(policyName)); return; } var msg = new UrlEncodedMessage("policy") { { "name" , policy.Name }, { "description" , policy.Description}, }; // msg.AddCollection("sids",policy.Sids); msg.AddCollection("accounts", policy.Accounts); WriteAsync(msg); }) Link To Source File
coapp Session.cs Task.Factory.StartNew(() => { new PackageManagerMessages { RequestId = requestMessage["rqid"], }.Extend(_messages).Register(); if (!_packageManagerSession.CheckForPermission(PermissionPolicy.ModifyPolicy)) { PackageManagerMessages.Invoke.PermissionRequired("ModifyPolicy"); return; } var policyName = requestMessage["name"].ToString(); var policy = PermissionPolicy.AllPolicies.Where(each => each.Name.Equals(policyName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault(); if (policy == null) { SendMessageArgumentError("add-to-policy", "name", "policy '{0}' not found".format(policyName)); return; } try { policy.Add(requestMessage["account"]); } catch { SendMessageArgumentError("add-to-policy", "account", "policy '{0}' could not add account '{1}'".format(policyName, requestMessage["account"])); } }) Link To Source File
coapp Session.cs Task.Factory.StartNew(() => { new PackageManagerMessages { RequestId = requestMessage["rqid"], }.Extend(_messages).Register(); if (!_packageManagerSession.CheckForPermission(PermissionPolicy.ModifyPolicy)) { PackageManagerMessages.Invoke.PermissionRequired("ModifyPolicy"); return; } var policyName = requestMessage["name"].ToString(); var policy = PermissionPolicy.AllPolicies.Where(each => each.Name.Equals(policyName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault(); if (policy == null) { SendMessageArgumentError("remove-from-policy", "name", "policy '{0}' not found".format(policyName)); return; } try { policy.Remove(requestMessage["account"]); } catch { SendMessageArgumentError("remove-from-policy", "account", "policy '{0}' could not remove account '{1}'".format(policyName, requestMessage["account"])); } }) Link To Source File
coapp Session.cs Task.Factory.StartNew(() => { // at this point the only thing we are monitoring is the InstalledPackagesFeed. new PackageManagerMessages { RequestId = requestMessage["rqid"], }.Extend(_messages).Register(); var percent = 0; do { Thread.Sleep(10); var p = InstalledPackageFeed.Instance.Progress; if( p > percent) { percent =p ; WriteAsync(new UrlEncodedMessage("engine-status") { { "percent-complete", percent }, }); } } while (percent < 100); }) Link To Source File
coapp Rehash.cs // signal rehash to proceed. Task.Factory.StartNew(() => { Thread.Sleep(1000); Logger.Message("Rehash: Triggering Global Event"); Kernel32.SetEvent(_globalResetEvent); Thread.Sleep(1000); // give everyone a chance to wake up and do their job Kernel32.ResetEvent(_globalResetEvent); }) Link To Source File
devtools QtAppContext.cs // Task.Factory.StartNew(() => { // make call to http://pygments.appspot.com to with lang=brushName and code=$code to get html var request = (HttpWebRequest) WebRequest.Create("http://pygments.appspot.com"); request.Method = "POST"; request.BeginGetRequestStream( xx => { var postStream = request.EndGetRequestStream(xx); var postArray = Encoding.UTF8.GetBytes("lang={0}&code={1}".format(brushName.UrlEncode(), clipSource.UrlEncode())); postStream.Write(postArray, 0, postArray.Length ); postStream.Close(); request.BeginGetResponse( x => { try { var response = (HttpWebResponse)request.EndGetResponse(x); using (var stream = response.GetResponseStream()) { using (var sr = new StreamReader(stream, System.Text.Encoding.GetEncoding("utf-8"))) { var html = htmlTemplate.format(Themes[theme],sr.ReadToEnd()); try { var ftp = Connect(); if (ftp == null) { return; } ftp.ChangeDir(RegistryView.ApplicationUser["#ftp-folder"].StringValue); var remoteFilename = Path.ChangeExtension(RegistryView.ApplicationUser["#image-filename-template"].StringValue.FormatFilename(), "html"); using (var stream2 = new MemoryStream(Encoding.UTF8.GetBytes(html))) { stream2.Seek(0, SeekOrigin.Begin); ftp.UploadAndComplete(stream2, stream2.Length, remoteFilename, false); } Invoke( () => { var finishedUrl = RegistryView.ApplicationUser["#image-finishedurl-template"].StringValue.format(remoteFilename); ShowBalloonTip("Text uploaded", finishedUrl, ToolTipIcon.Info); try { if (AudioCues) { beep.Play(); } Clipboard.SetDataObject(finishedUrl, true, 3, 100); } catch { /* suppress */ } }); } catch { /* suppress */ } } } } catch { if (AudioCues) { errorBeep.Play(); } ShowBalloonTip("Unable to get shortened URL", "Did you set your Bit.ly credentials?", ToolTipIcon.Error); } }, request); }, request); }) Link To Source File
devtools QtAppContext.cs Task.Factory.StartNew(() => { try { var ftp = Connect(); if (ftp == null) { return; } ftp.ChangeDir(RegistryView.ApplicationUser["#ftp-folder"].StringValue); if (stream != null) { remoteFilename = RegistryView.ApplicationUser["#image-filename-template"].StringValue.FormatFilename(); ftp.OpenUpload(stream, stream.Length, remoteFilename, false); ftp.DoUploadUntilComplete(); stream.Close(); stream.Dispose(); } if (filenames != null) { string html = @"Files:
"; foreach (var file in filenames) { if (Directory.Exists(file)) { foreach (var subFile in Directory.GetFiles(file, "*", SearchOption.AllDirectories)) { var subPath = Path.GetDirectoryName(file).GetSubPath(subFile); var subFolder = Path.GetDirectoryName(subPath); foreach (var folder in subFolder.Split(new[] {'//'}, StringSplitOptions.RemoveEmptyEntries)) { ftp.ChangeDirMakeIfNeccesary(folder); } remoteFilename = Path.GetFileName(subFile); ftp.OpenUpload(subFile, remoteFilename, false); ftp.DoUploadUntilComplete(); filesUploaded++; remoteFilename = Path.Combine(subFolder, Path.GetFileName(subFile)).Replace('//', '/'); html += @"". format( RegistryView.ApplicationUser["#image-finishedurl-template"].StringValue.format(remoteFilename), remoteFilename, new FileInfo(subFile).Length); ftp.ChangeDir("/"); ftp.ChangeDir(RegistryView.ApplicationUser["#ftp-folder"].StringValue); } } else { try { remoteFilename = Path.GetFileName(file); ftp.OpenUpload(file, remoteFilename, false); ftp.DoUploadUntilComplete(); filesUploaded++; html += @"". format( RegistryView.ApplicationUser["#image-finishedurl-template"].StringValue.format(remoteFilename), remoteFilename, new FileInfo(file).Length); } catch { /* suppress */ } } } if (filesUploaded > 1) { html += @"
FileSize
{1}{2:n0}
{1}{2:n0}
"; remoteFilename = Path.ChangeExtension(RegistryView.ApplicationUser["#image-filename-template"].StringValue.FormatFilename(), "html"); try { stream = new MemoryStream(Encoding.UTF8.GetBytes(html)); ftp.OpenUpload(stream, stream.Length, remoteFilename, false); ftp.DoUploadUntilComplete(); stream.Close(); stream.Dispose(); } catch { /* suppress */ } } } ftp.Disconnect(); } catch { /* suppress */ } Invoke(() => { var finishedUrl = RegistryView.ApplicationUser["#image-finishedurl-template"].StringValue.format(remoteFilename); ShowBalloonTip("Image uploaded", finishedUrl, ToolTipIcon.Info); try { Clipboard.SetDataObject(finishedUrl, true, 3, 100); } catch { /* suppress */ } }); })
Link To Source File
devtools CommitMessageHandler.cs Task.Factory.StartNew( () => { try { dynamic json = JObject.Parse(payload); Console.WriteLine("MSG Process begin {0}", json.commits.Count); var count = json.commits.Count; var doSiteRebuild = false; for (int i = 0; i < count; i++) { var username = json.commits[i].author.username.Value; var commitMessage = json.commits[i].message.Value; var repository = json.repository.name.Value; var url = (string)json.commits[i].url.Value; if (repository == "coapp.org") { doSiteRebuild = true; } Bitly.Shorten(url).ContinueWith( (bitlyAntecedent) => { var commitUrl = bitlyAntecedent.Result; var handle = _aliases.ContainsKey(username) ? _aliases[username] : username; var sz = repository.Length + handle.Length + commitUrl.Length + commitMessage.Length + 10; var n = 140 - sz; if (n < 0) { commitMessage = commitMessage.Substring(0, (commitMessage.Length + n) - 3) + "..."; } _tweeter.Tweet("[{0}]=>{1} via {2} {3}", repository, commitMessage, handle, commitUrl); Console.WriteLine("[{0}]=>{1} via {2} {3}", repository, commitMessage, handle, commitUrl); }); } // just rebuild the site once for a given batch of rebuild commit messages. if( doSiteRebuild) { Task.Factory.StartNew(() => { try { Console.WriteLine("Rebuilding website."); Console.WriteLine("(1) Pulling from github"); Environment.CurrentDirectory = @"c:/tools/new_coapp.org"; if (_cmdexe.Exec(@"/c git.cmd pull") != 0) { Console.WriteLine("Git Pull Failure:/r/n{0}", _cmdexe.StandardOut); return; } Console.WriteLine("(2) Running DocPad Generate"); var node = new ProcessUtility(@"tools/node.exe"); if (node.Exec(@"node_modules/coffee-script/bin/coffee node_modules/docpad/bin/docpad generate") != 0) { Console.WriteLine("DocPad Failure:/r/n{0}", node.StandardOut); return; } Console.WriteLine("(3) Robocopying the site into the live directory"); if (_robocopy.Exec(@"/MIR c:/tools/new_coapp.org/out e:/sitesroot/0") != 0) { Console.WriteLine("Robocopy Failure:/r/n{0}", _robocopy.StandardOut); return; } Console.WriteLine("Rebuilt Website."); } catch( Exception e ) { Console.WriteLine("Error: {0} -- {1}/r/n{2}", e.GetType(), e.Message, e.StackTrace); } }); } } catch(Exception e) { Console.WriteLine("Error handling uploaded package: {0} -- {1}/r/n{2}", e.GetType(), e.Message, e.StackTrace); response.StatusCode = 500; response.Close(); } }, TaskCreationOptions.AttachedToParent) Link To Source File
devtools CommitMessageHandler.cs Task.Factory.StartNew(() => { try { Console.WriteLine("Rebuilding website."); Console.WriteLine("(1) Pulling from github"); Environment.CurrentDirectory = @"c:/tools/new_coapp.org"; if (_cmdexe.Exec(@"/c git.cmd pull") != 0) { Console.WriteLine("Git Pull Failure:/r/n{0}", _cmdexe.StandardOut); return; } Console.WriteLine("(2) Running DocPad Generate"); var node = new ProcessUtility(@"tools/node.exe"); if (node.Exec(@"node_modules/coffee-script/bin/coffee node_modules/docpad/bin/docpad generate") != 0) { Console.WriteLine("DocPad Failure:/r/n{0}", node.StandardOut); return; } Console.WriteLine("(3) Robocopying the site into the live directory"); if (_robocopy.Exec(@"/MIR c:/tools/new_coapp.org/out e:/sitesroot/0") != 0) { Console.WriteLine("Robocopy Failure:/r/n{0}", _robocopy.StandardOut); return; } Console.WriteLine("Rebuilt Website."); } catch( Exception e ) { Console.WriteLine("Error: {0} -- {1}/r/n{2}", e.GetType(), e.Message, e.StackTrace); } }) Link To Source File
devtools UploadedFileHandler.cs Task.Factory.StartNew( () => { var filename = "UploadedFile.bin".GenerateTemporaryFilename(); File.WriteAllBytes(filename, data); PackageManager.Instance.ConnectAndWait("RepositoryService", null, 5000); // verify that the file is actually a valid package PackageManager.Instance.GetPackages(filename, messages: RepositoryServiceMain._messages).ContinueWith( antecedent => { if( antecedent.IsFaulted ) { Console.WriteLine("Fault occurred after upload: {0}", filename); filename.TryHardToDelete(); response.StatusCode = 400; response.Close(); return; } if( antecedent.IsCanceled) { Console.WriteLine("Request was cancelled"); filename.TryHardToDelete(); response.StatusCode = 400; response.Close(); return; } var pkg = antecedent.Result.FirstOrDefault(); if( pkg == null ) { Console.WriteLine("File uploaded is not recognized as a package: {0}", filename); filename.TryHardToDelete(); response.StatusCode = 400; response.Close(); return; } var targetFilename = (pkg.CanonicalName + ".msi").ToLower(); var location = new Uri(_packagePrefixUrl, targetFilename); PackageManager.Instance.GetPackageDetails(pkg.CanonicalName, RepositoryServiceMain._messages).Wait(); //copy the package to the destination if (_cloudFileSystem != null) { // copy file to azure storage _cloudFileSystem.WriteBlob(_packageStorageFolder, targetFilename, filename, false, (progress) => { ConsoleExtensions.PrintProgressBar("{0} => {1}".format(pkg.CanonicalName, _packageStorageFolder), progress); }); if (pkg.Name.Equals("coapp.toolkit", StringComparison.CurrentCultureIgnoreCase) && pkg.PublicKeyToken.Equals("820d50196d4e8857", StringComparison.CurrentCultureIgnoreCase)) { // update the default toolkit too _cloudFileSystem.WriteBlob(_packageStorageFolder, "coapp.toolkit.msi", filename, false, (progress) => { ConsoleExtensions.PrintProgressBar("{0} => {1}".format(_localfeedLocation, _packageStorageFolder), progress); }); Console.WriteLine(); } if (pkg.Name.Equals("coapp.devtools", StringComparison.CurrentCultureIgnoreCase) && pkg.PublicKeyToken.Equals("820d50196d4e8857", StringComparison.CurrentCultureIgnoreCase)) { // update the default toolkit too _cloudFileSystem.WriteBlob(_packageStorageFolder, "coapp.devtools.msi", filename, false, (progress) => { ConsoleExtensions.PrintProgressBar("{0} => {1}".format(_localfeedLocation, _packageStorageFolder), progress); }); Console.WriteLine(); } // remove the local file, since we don't need it anymore. filename.TryHardToDelete(); Console.WriteLine(); } else { var targetLocation = Path.Combine(_packageStorageFolder, targetFilename); if( File.Exists(targetLocation)) { targetLocation.TryHardToDelete(); } File.Copy(filename, targetLocation); } lock(typeof(UploadedFileHandler)) { // update the feed var Feed = new AtomFeed(); if (!string.IsNullOrEmpty(_localfeedLocation) && File.Exists(_localfeedLocation)) { var originalFeed = AtomFeed.LoadFile(_localfeedLocation); Feed.Add(originalFeed.Items.Where(each => each is AtomItem).Select(each => each as AtomItem)); } if (!string.IsNullOrEmpty(pkg.PackageItemText)) { var item = SyndicationItem.Load(XmlReader.Create(new StringReader(pkg.PackageItemText))); var feedItem = Feed.Add(item); // first, make sure that the feeds contains the intended feed location. if (feedItem.Model.Feeds == null) { feedItem.Model.Feeds = new List(); } if (!feedItem.Model.Feeds.Contains(_canonicalFeedUrl)) { feedItem.Model.Feeds.Insert(0, _canonicalFeedUrl); } if (feedItem.Model.Locations == null) { feedItem.Model.Locations = new List(); } if (!feedItem.Model.Locations.Contains(location)) { feedItem.Model.Locations.Insert(0, location); } } Feed.Save(_localfeedLocation); if (_cloudFileSystem != null) { _cloudFileSystem.WriteBlob(_packageStorageFolder, Path.GetFileName(_localfeedLocation).ToLower() , _localfeedLocation, false, (progress) => { ConsoleExtensions.PrintProgressBar("{0} => {1}".format(_localfeedLocation, _packageStorageFolder), progress); }); Console.WriteLine(); _cloudFileSystem.WriteBlob(_packageStorageFolder, Path.GetFileName(_localfeedLocation).ToLower()+".gz", _localfeedLocation, true, (progress) => { ConsoleExtensions.PrintProgressBar("{0} => {1}".format(_localfeedLocation+".gz", _packageStorageFolder), progress); }); Console.WriteLine(); } } // Advertise the package on twitter if (_tweeter != null) { // pkg.Name Bitly.Shorten(location.AbsoluteUri).ContinueWith( (x) => { var name = "[{0}-{1}-{2}]".format(pkg.Name, pkg.Version, pkg.Architecture); var summary = pkg.Summary; var l1 = 138 - (name.Length + x.Result.Length); if( summary.Length > l1 ) { summary = summary.Substring(0, l1 - 1) + "/u2026"; } var text = "{0} {1} {2}".format(name, summary, x.Result); Console.WriteLine("Tweet: {0}",text); _tweeter.Tweet(text); }); } response.StatusCode = 200; response.Close(); }, TaskContinuationOptions.AttachedToParent); }) Link To Source File
devtools SimpleSignerMain.cs Task.Factory.StartNew(() => { if (CoApp.Toolkit.Crypto.Verifier.HasValidSignature(filename) && !_resign) { results.Add( new FileResult {FullPath= filename, AlreadySigned = true, OriginalMD5 = filename.GetFileMD5(), Message = "Already Signed (skipped)", Color = ConsoleColor.Yellow}); return; } try { var info = PEInfo.Scan(filename); if (info.IsPEBinary) { var peBinary = PeBinary.Load(filename); lock (binaries) { if (!binaries.Contains(peBinary)) { binaries.Add(peBinary); } foreach (var depBinary in peBinary.UnsignedDependentBinaries.Where(depBinary => !binaries.Contains(depBinary))) { binaries.Add(depBinary); } } } else { if (!nonBinaries.Contains(info)) { nonBinaries.Add(info); } } } catch (Exception e) { results.Add(new FileResult { FullPath = filename, Message = "Failed to load--{0}".format(e.GetType()), Color = ConsoleColor.Red }); } }) Link To Source File
devtools SimpleSignerMain.cs Task.Factory.StartNew(() => { var filename = nonBinary.Filename; try { PeBinary.SignFile(filename, _certificate); results.Add( new FileResult { FullPath = filename, OriginalMD5 = nonBinary.MD5, NewMD5 = filename.GetFileMD5(), Message = "Success." }); } catch (DigitalSignFailure exc) { if (exc.Win32Code == 0x800b0003) { results.Add(new FileResult { FullPath = filename, OriginalMD5 = nonBinary.MD5, Message = "Unable to sign unrecognized file", Color = ConsoleColor.Red }); } else { results.Add(new FileResult {FullPath = filename, OriginalMD5 = nonBinary.MD5, Message = exc.Message, Color = ConsoleColor.Red}); } } catch (CoAppException exc) { results.Add(new FileResult { FullPath = filename, OriginalMD5 = nonBinary.MD5, Message = exc.Message, Color = ConsoleColor.Red }); } catch (Exception exc) { results.Add(new FileResult { FullPath = filename, OriginalMD5 = nonBinary.MD5, Message = "Unable to sign unrecognized, non-binary file--{0}".format(exc.GetType()), Color = ConsoleColor.Red}); } }) Link To Source File
devtools SimpleSignerMain.cs Task.Factory.StartNew(() => { var filename = peBinary.Filename; try { if (_strongname) { peBinary.StrongNameKeyCertificate = _certificate; } if (_sign) { peBinary.SigningCertificate = _certificate; } if (_company != null) { peBinary.CompanyName = _company; } if (_description != null) { peBinary.FileDescription = _description; } if (_internalName != null) { peBinary.InternalName = _internalName; } if (_copyright != null) { peBinary.LegalCopyright = _copyright; } if (_originalFilename != null) { peBinary.OriginalFilename = _originalFilename; } if (_productName != null) { peBinary.ProductName = _productName; } if (_productVersion != null) { peBinary.ProductVersion = _productVersion; } if (_fileVersion != null) { peBinary.FileVersion = _fileVersion; } peBinary.Save(_auto); results.Add(new FileResult { FullPath = filename, OriginalMD5 = peBinary.Info.MD5, NewMD5 = filename.GetFileMD5(), Message = "Success" }); } catch (CoAppException exc) { results.Add(new FileResult { FullPath = filename, OriginalMD5 = peBinary.Info.MD5, Message = exc.Message, Color = ConsoleColor.Red }); } catch (Exception exc) { results.Add(new FileResult { FullPath = filename, OriginalMD5 = peBinary.Info.MD5, Message = "Unable to sign PE Binary file--{0}".format(exc.GetType()), Color = ConsoleColor.Red }); } }) Link To Source File
devtools PeBinary.cs Task.Factory.StartNew(() => { using (var ri = new ResourceInfo()) { // lets pull out the relevant resources first. ri.Load(_filename); try { var versionKey = ri.Resources.Keys.Where(each => each.ResourceType == ResourceTypes.RT_VERSION).FirstOrDefault(); var versionResource = ri.Resources[versionKey].First() as VersionResource; var versionStringTable = (versionResource["StringFileInfo"] as StringFileInfo).Strings.Values.First(); _comments = TryGetVersionString(versionStringTable, "Comments"); _companyName = TryGetVersionString(versionStringTable, "CompanyName"); _productName = TryGetVersionString(versionStringTable, "ProductName"); _assemblyVersion = TryGetVersionString(versionStringTable, "Assembly Version"); _fileVersion = TryGetVersionString(versionStringTable, "FileVersion"); _internalName = TryGetVersionString(versionStringTable, "InternalName"); _originalFilename = TryGetVersionString(versionStringTable, "OriginalFilename"); _legalCopyright = TryGetVersionString(versionStringTable, "LegalCopyright"); _legalTrademarks = TryGetVersionString(versionStringTable, "LegalTrademarks"); _fileDescription = TryGetVersionString(versionStringTable, "FileDescription"); _bugTracker = TryGetVersionString(versionStringTable, "BugTracker"); } catch { // skip it if this fails. } } if (IsManaged) { // we can read in the binary using CCI try { if (MutableAssembly != null) { // we should see if we can get assembly attributes, since sometimes they can be set, but not the native ones. foreach (var a in MutableAssembly.ContainingAssembly.AssemblyAttributes) { var attributeArgument = (a.Arguments.FirstOrDefault() as MetadataConstant); if (attributeArgument != null) { var attributeName = a.Type.ToString(); var attributeValue = attributeArgument.Value.ToString(); if (!string.IsNullOrEmpty(attributeValue)) { switch (attributeName) { case "System.Reflection.AssemblyTitleAttribute": if (string.IsNullOrEmpty(AssemblyTitle)) { AssemblyTitle = attributeValue; } break; case "System.Reflection.AssemblyCompanyAttribute": if (string.IsNullOrEmpty(AssemblyCompany)) { AssemblyCompany = attributeValue; } break; case "System.Reflection.AssemblyProductAttribute": if (string.IsNullOrEmpty(AssemblyProduct)) { AssemblyProduct = attributeValue; } break; case "System.Reflection.AssemblyVersionAttribute": if (string.IsNullOrEmpty(AssemblyVersion)) { AssemblyVersion = attributeValue; } break; case "System.Reflection.AssemblyFileVersionAttribute": if (string.IsNullOrEmpty(AssemblyFileVersion)) { AssemblyFileVersion = attributeValue; } if (string.IsNullOrEmpty(_productVersion)) { _productVersion = attributeValue; } break; case "System.Reflection.AssemblyCopyrightAttribute": if (string.IsNullOrEmpty(AssemblyCopyright)) { AssemblyCopyright = attributeValue; } break; case "System.Reflection.AssemblyTrademarkAttribute": if (string.IsNullOrEmpty(AssemblyTrademark)) { AssemblyTrademark = attributeValue; } break; case "System.Reflection.AssemblyDescriptionAttribute": if (string.IsNullOrEmpty(AssemblyDescription)) { AssemblyDescription = attributeValue; } break; case "BugTrackerAttribute": if (string.IsNullOrEmpty(BugTracker)) { BugTracker = attributeValue; } break; } } } } } _pendingChanges = false; } catch { } } }) Link To Source File
_bootstrapperui_deprecated Logger.cs Task.Factory.StartNew(() => { while (!EventLog.SourceExists(Source)) { Thread.Sleep(20); } _ready = true; }) Link To Source File
_bootstrapperui_deprecated Logger.cs Task.Factory.StartNew(() => { for (var i = 0; i < 100 && !_ready; i++) { Thread.Sleep(50); } // go ahead and try, but don't whine if this gets dropped. try { _eventLog.WriteEntry(message, type, eventID, category, rawData); } catch { } }) Link To Source File
_bootstrapperui_deprecated SingleStep.cs Task.Factory.StartNew(() => { try { Logger.Warning("Started Toolkit Installer"); // Thread.Sleep(4000); NativeMethods.MsiSetInternalUI(2, IntPtr.Zero); NativeMethods.MsiSetExternalUI((context, messageType, message) => 1, 0x400, IntPtr.Zero); if (!Cancelling) { var file = MsiFilename; // if this is the CoApp MSI, we don't need to fetch the CoApp MSI. if (!IsCoAppToolkitMSI(MsiFilename)) { // get coapp.toolkit.msi file = AcquireFile("CoApp.Toolkit.msi", percentDownloaded => ActualPercent = percentDownloaded / 10); if (!IsCoAppToolkitMSI(file)) { MainWindow.Fail(LocalizedMessage.IDS_UNABLE_TO_ACQUIRE_COAPP_INSTALLER, "Unable to download the CoApp Installer MSI"); return; } } // We made it past downloading. ActualPercent = 10; // bail if someone has told us to. (good luck!) if (Cancelling) { return; } // get a reference to the delegate. uihandler = UiHandler; NativeMethods.MsiSetExternalUI(uihandler, 0x400, IntPtr.Zero); try { var CoAppCacheFolder = Path.Combine(CoAppRootFolder.Value, ".cache"); Directory.CreateDirectory(CoAppCacheFolder); var cachedPath = Path.Combine(CoAppCacheFolder, MsiCanonicalName + ".msi"); if (!File.Exists(cachedPath)) { File.Copy(file, cachedPath); } } catch (Exception e) { Logger.Error(e); } Logger.Warning("Running MSI"); // install CoApp.Toolkit msi. Don't blink, this can happen FAST! var result = NativeMethods.MsiInstallProduct(file, String.Format(@"TARGETDIR=""{0}/.installed/"" ALLUSERS=1 COAPP_INSTALLED=1 REBOOT=REALLYSUPPRESS", CoAppRootFolder.Value)); // set the ui hander back to nothing. NativeMethods.MsiSetExternalUI(null, 0x400, IntPtr.Zero); InstallTask = null; // after this point, all you can do is exit the installer. Logger.Warning("Done Installing MSI (rc={0}.",result); // did we succeed? if (result == 0) { ActualPercent = 80; // if the UI has not shown, it will try short circuit in the window constructor. // bail if someone has told us to. (good luck!) if (Cancelling) { return; } // we'll not be on the GUI thread when this runs. RunInstaller(false); } else { MainWindow.Fail(LocalizedMessage.IDS_CANT_CONTINUE, "Installation Engine failed to install. o_O"); } } } catch( Exception e ) { Logger.Error(e); MainWindow.Fail(LocalizedMessage.IDS_SOMETHING_ODD, "This can't be good."); } finally { InstallTask = null; } // if we got to this point, kinda feels like we should be failing }) Link To Source File
_bootstrapperui_deprecated MainWindow.xaml.cs Task.Factory.StartNew(() => { if (NativeResources.Value != null) { Dispatcher.Invoke((Action)delegate { containerPanel.Background.SetValue(ImageBrush.ImageSourceProperty, NativeResources.Value.GetBitmapImage(1201)); logoImage.SetValue(Image.SourceProperty, NativeResources.Value.GetBitmapImage(1202)); }); Logger.Warning("Loaded Resources."); } else { Logger.Warning("Unable to load resources Continuing anyway."); } }) Link To Source File
_toolkit_deprecated AsyncConsoleProgram.cs Task.Factory.StartNew(() => { #if DEBUG new DebugMessage { WriteLine = (text) => { Console.WriteLine("[DEBUG][{0}] {1}", ++Counter,text); } }.Register(); #endif Main(args); }, CancellationTokenSource.Token) Link To Source File
_toolkit_deprecated Logger.cs Task.Factory.StartNew(() => { while (!EventLog.SourceExists(Source)) { Thread.Sleep(20); } _ready = true; }) Link To Source File
_toolkit_deprecated Logger.cs Task.Factory.StartNew(() => { for (var i = 0; i < 20 && !_ready; i++) { Thread.Sleep(10); } // go ahead and try, but don't whine if this gets dropped. try { _eventLog.WriteEntry(message, type, (short)pid, (short)category, rawData); } catch { } }) Link To Source File
_toolkit_deprecated EnvironmentUtility.cs #if COAPP_ENGINE_CORE Rehash.ForceProcessToReloadEnvironment("explorer"); Rehash.ForceProcessToReloadEnvironment("services"); #else Task.Factory.StartNew(() => { User32.SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, "Environment", SMTO_ABORTIFHUNG, 1000, IntPtr.Zero); }) Link To Source File
_toolkit_deprecated Downloader.cs Task.Factory.StartNew(() => { foreach (var location in locations) { try { var uri = new Uri(location); if (uri.IsFile) { // try to copy the file local. var remoteFile = uri.AbsoluteUri.CanonicalizePath(); // if this fails, we'll just move down the line. File.Copy(remoteFile, targetFilename); PackageManager.Instance.RecognizeFile(canonicalName, targetFilename, uri.AbsoluteUri, new PackageManagerMessages().Extend(messages)); return; } Task progressTask = null; var rf = RemoteFile.GetRemoteFile(uri, targetFilename); rf.Get(new RemoteFileMessages { Completed = (itemUri) => { PackageManager.Instance.RecognizeFile(canonicalName, targetFilename, uri.AbsoluteUri, new PackageManagerMessages().Extend(messages)); if( remoteFileMessages != null ) { remoteFileMessages.Completed(itemUri); } }, Failed = (itemUri) => { if (File.Exists(targetFilename)) { targetFilename.TryHardToDelete(); if( remoteFileMessages != null ) { remoteFileMessages.Failed(itemUri); } } }, Progress = (itemUri, percent) => { if (progressTask == null) { progressTask = PackageManager.Instance.DownloadProgress(canonicalName, percent); progressTask.ContinueWith((antecedent) => { progressTask = null; }); } if( remoteFileMessages != null ) { remoteFileMessages.Progress(itemUri, percent); } } }).Wait(); if (File.Exists(targetFilename)) { return; } } catch { // bogus, dude. // try the next one. } } PackageManager.Instance.UnableToAcquire(canonicalName, new PackageManagerMessages()); }, TaskCreationOptions.AttachedToParent) Link To Source File
_toolkit_deprecated Installer.cs Task.Factory.StartNew(StartInstall) Link To Source File
_toolkit_deprecated PackageManager.cs Task.Factory.StartNew(() => { #if DEBUG EngineServiceManager.EnsureServiceIsResponding(true); #else EngineServiceManager.EnsureServiceIsResponding(); #endif sessionId = sessionId ?? Process.GetCurrentProcess().Id.ToString(); for (int count = 0; count < 60; count++) { _pipe = new NamedPipeClientStream(".", "CoAppInstaller", PipeDirection.InOut, PipeOptions.Asynchronous, TokenImpersonationLevel.Impersonation); try { _pipe.Connect(500); _pipe.ReadMode = PipeTransmissionMode.Message; break; } catch { _pipe = null; } } if( _pipe == null ) { throw new CoAppException("Unable to connect to CoApp Service"); } StartSession(clientName, sessionId); try { while (IsConnected) { var incomingMessage = new byte[BufferSize]; var readTask = _pipe.ReadAsync(incomingMessage, 0, BufferSize); readTask.ContinueWith(antecedent => { if (antecedent.IsCanceled || antecedent.IsFaulted || !IsConnected) { Disconnect(); return; } var rawMessage = Encoding.UTF8.GetString(incomingMessage, 0, antecedent.Result); if (string.IsNullOrEmpty(rawMessage)) { return; } var responseMessage = new UrlEncodedMessage(rawMessage); int? rqid = responseMessage["rqid"]; Logger.Message("Response:{0}".format(responseMessage.ToSmallerString())); try { ManualEventQueue.GetQueue(rqid.GetValueOrDefault()).Enqueue(responseMessage); } catch { if (responseMessage.Command.Equals("session-started")) { if( Connected != null ) { Connected(); } return; } // Console.WriteLine("Unable to queue the response to the right request event queue!"); // Console.WriteLine(" Response:{0}", responseMessage.Command); // not able to queue up the response to the right task? } }).AutoManage(); readTask.Wait(); } } catch (Exception e) { Logger.Message("Connection Terminating with Exception {0}/{1}", e.GetType(), e.Message); } finally { Disconnect(); } }) Link To Source File
_toolkit_deprecated PackageManager.cs Task.Factory.StartNew(Disconnected) Link To Source File
_toolkit_deprecated PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("find-packages") { {"canonical-name", canonicalName}, {"name", name}, {"version", version}, {"arch", arch}, {"public-key-token", publicKeyToken}, {"dependencies", dependencies}, {"installed", installed}, {"active", active}, {"required", required}, {"blocked", blocked}, {"latest", latest}, {"index", index}, {"max-results", maxResults}, {"location", location}, {"force-scan", forceScan}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
_toolkit_deprecated PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("get-package-details") { {"canonical-name", canonicalName}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
_toolkit_deprecated PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("install-package") { {"canonical-name", canonicalName}, {"auto-upgrade", autoUpgrade}, {"force", force}, {"download", download}, {"pretend", pretend}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
_toolkit_deprecated PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("find-feeds") { {"index", index}, {"max-results", maxResults}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
_toolkit_deprecated PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("remove-feed") { {"location", location}, {"session", session}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
_toolkit_deprecated PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("add-feed") { {"location", location}, {"session", session}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
_toolkit_deprecated PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("verify-file-signature") { {"filename", filename}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
_toolkit_deprecated PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("set-package") { {"canonical-name", canonicalName}, {"active", active}, {"required", required}, {"blocked", blocked}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
_toolkit_deprecated PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("remove-package") { {"canonical-name", canonicalName}, {"force", force}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
_toolkit_deprecated PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("unable-to-acquire") { {"canonical-name", canonicalName}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
_toolkit_deprecated PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("download-progress") { {"canonical-name", canonicalName}, {"progress", progress.ToString()}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
_toolkit_deprecated PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("recognize-file") { {"canonical-name", canonicalName}, {"local-location", localLocation}, {"remote-location", remoteLocation}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
_toolkit_deprecated PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("suppress-feed") { {"location", location}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
_toolkit_deprecated PackageManager.cs Task.Factory.StartNew(() => { using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("set-logging") { {"messages", Messages}, {"warnings", Warnings}, {"errors", Errors}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
_toolkit_deprecated PackageManager.cs Task.Factory.StartNew( () => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("get-engine-status") { {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
_toolkit_deprecated PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("get-policy") { {"name", policyName}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
_toolkit_deprecated PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("add-to-policy") { {"name", policyName}, {"account", account}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
_toolkit_deprecated PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("remove-from-policy") { {"name", policyName}, {"account", account}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
_toolkit_deprecated PackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } using (var eventQueue = new ManualEventQueue()) { WriteAsync(new UrlEncodedMessage("symlink") { {"existing-location", existingLocation}, {"new-link", newLink}, {"link-type", linkType.ToString()}, {"rqid", Task.CurrentId}, }); // will return when the final message comes thru. eventQueue.DispatchResponses(); } }) Link To Source File
_toolkit_deprecated EngineService.cs // make sure coapp is properly set up. Task.Factory.StartNew(() => { try { Logger.Warning("Gonna make sure stuff is setup right."); // this ensures that composition rules are run for toolkit. Package.EnsureCanonicalFoldersArePresent(); Logger.Warning("Getting Version of CoApp."); var v = Package.GetCurrentPackageVersion("coapp.toolkit", "820d50196d4e8857"); Logger.Warning("CoApp Version : " + v); } catch (Exception e ) { Logger.Error(e); } }) Link To Source File
_toolkit_deprecated EngineService.cs Task.Factory.StartNew(() => { try { Logger.Message("Service Restart Order Issued."); // make sure nobody else can connect. _instance.Value._cancellationTokenSource.Cancel(); // tell the clients to go away. Logger.Message("Telling clients to go away."); Session.NotifyClientsOfRestart(); Logger.Message("Waiting up to 30 seconds for clients to disconnect."); // I'll give you 30 seconds to get lost. for (var i = 0; i < 300 && Session.HasActiveSessions; i++) { Thread.Sleep(100); } if (Session.HasActiveSessions) { Logger.Message("Forcing Disconnection of clients."); Session.CancelAll(); } } catch(Exception e) { Logger.Error(e); } Logger.Message("Clients should be disconnected; forcing restart"); if (IsInteractive) { Process.Start(new ProcessStartInfo { FileName = Assembly.GetEntryAssembly().Location, Arguments = "--interactive" }); Environment.Exit(0); } else { Process.Start(new ProcessStartInfo { FileName = Assembly.GetEntryAssembly().Location, Arguments = "--restart" }); } }) Link To Source File
_toolkit_deprecated NewPackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("find-package"); return; } if (!PackageManagerSession.Invoke.CheckForPermission(PermissionPolicy.EnumeratePackages)) { PackageManagerMessages.Invoke.PermissionRequired("EnumeratePackages"); return; } UpdateIsRequestedFlags(); // get basic list of packages based on primary characteristics if (!string.IsNullOrEmpty(canonicalName)) { // if canonical name is passed, override name,version,pkt,arch with the parsed canonicalname. var match = _canonicalNameParser.Match(canonicalName.ToLower()); if (!match.Success) { PackageManagerMessages.Invoke.Error("find-packages", "canonical-name", "Canonical name '{0}' does not appear to be a valid canonical name".format(canonicalName)); return; } name = match.Groups[1].Captures[0].Value; version = match.Groups[2].Captures[0].Value; arch = match.Groups[3].Captures[0].Value; publicKeyToken = match.Groups[4].Captures[0].Value; } if( forceScan == true ) { foreach( var feed in Feeds ) { feed.Stale = true; } } var results = SearchForPackages(name, version, arch, publicKeyToken, location); // filter results of list based on secondary filters results = from package in results where (installed == null || package.IsInstalled == installed) && (active == null || package.IsActive == active) && (required == null || package.IsRequired == required) && (blocked == null || package.IsBlocked == blocked) select package; // only the latest? if (latest == true) { results = results.HighestPackages(); } // if the client has asked for the dependencies as well, include them in the result set. // otherwise the client will get the names in if (dependencies == true) { // grab the dependencies too. var deps = results.SelectMany(each => each.InternalPackageData.Dependencies).Distinct(); if (latest == true) { deps = deps.HighestPackages(); } results = results.Union(deps).Distinct(); } // paginate the results if (index.HasValue) { results = results.Skip(index.Value); } if (maxResults.HasValue) { results = results.Take(maxResults.Value); } if (results.Any()) { foreach (var package in results) { if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("find-packages"); return; } // otherwise, we're installing a dependency, and we need something compatable. var supercedents = (from p in SearchForPackages(package.Name, null, package.Architecture, package.PublicKeyToken) where p.InternalPackageData.PolicyMinimumVersion <= package.Version && p.InternalPackageData.PolicyMaximumVersion >= package.Version select p).OrderByDescending(p => p.Version).ToArray(); PackageManagerMessages.Invoke.PackageInformation(package, supercedents); } } else { PackageManagerMessages.Invoke.NoPackagesFound(); } }, TaskCreationOptions.AttachedToParent) Link To Source File
_toolkit_deprecated NewPackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("get-package-details"); return; } var package = GetSinglePackage(canonicalName, "get-package-details"); if (package == null) { return; } PackageManagerMessages.Invoke.PackageDetails(package); }, TaskCreationOptions.AttachedToParent) Link To Source File
_toolkit_deprecated NewPackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("install-package"); return; } var overallProgress = 0.0; var eachTaskIsWorth = 0.0; var numberOfPackagesToInstall = 0; var numberOfPackagesToDownload = 0; using (var manualResetEvent = new ManualResetEvent(true)) { try { lock (manualResetEvents) { manualResetEvents.Add(manualResetEvent); } var packagesTriedToDownloadThisTask = new List(); var package = GetSinglePackage(canonicalName, "install-package"); if (package == null) { PackageManagerMessages.Invoke.UnknownPackage(canonicalName); return; } // is the user authorized to install this? var highestInstalledPackage = SearchForInstalledPackages(package.Name, null, package.Architecture, package.PublicKeyToken).HighestPackages(); if (highestInstalledPackage.Any() && highestInstalledPackage.FirstOrDefault().Version < package.Version) { if (package.IsBlocked) { PackageManagerMessages.Invoke.PackageBlocked(canonicalName); return; } if (!PackageManagerSession.Invoke.CheckForPermission(PermissionPolicy.UpdatePackage)) { PackageManagerMessages.Invoke.PermissionRequired("UpdatePackage"); return; } } else { if (!PackageManagerSession.Invoke.CheckForPermission(PermissionPolicy.InstallPackage)) { PackageManagerMessages.Invoke.PermissionRequired("InstallPackage"); return; } } // mark the package as the client requested. package.PackageSessionData.DoNotSupercede = (false == autoUpgrade); package.PackageSessionData.UpgradeAsNeeded = (true == autoUpgrade); package.PackageSessionData.IsClientSpecified = true; // the resolve-acquire-install-loop do { // if the world changes, this will get set somewhere between here and the // other end of the do-loop. manualResetEvent.Reset(); if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("install-package"); return; } IEnumerable installGraph = null; try { installGraph = GenerateInstallGraph(package).ToArray(); } catch (OperationCompletedBeforeResultException) { // we encountered an unresolvable condition in the install graph. // messages should have already been sent. PackageManagerMessages.Invoke.FailedPackageInstall(canonicalName, package.InternalPackageData.LocalLocation, "One or more dependencies are unable to be resolved."); return; } // seems like a good time to check if we're supposed to bail... if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("install-package"); return; } if (download == false && pretend == true) { // we can just return a bunch of foundpackage messages, since we're not going to be // actually installing anything, nor trying to download anything. foreach( var p in installGraph) { PackageManagerMessages.Invoke.PackageInformation(package, Enumerable.Empty()); } return; } // we've got an install graph. // let's see if we've got all the files var missingFiles = from p in installGraph where !p.InternalPackageData.HasLocalLocation select p; if( download == true ) { // we want to try downloading all the files that we're missing, regardless if we've tried before. // unless we've already tried in this task once. foreach( var p in missingFiles.Where( each => packagesTriedToDownloadThisTask.Contains(each)) ) { packagesTriedToDownloadThisTask.Add(p); p.PackageSessionData.CouldNotDownload = false; } } if( numberOfPackagesToInstall != installGraph.Count() || numberOfPackagesToDownload != missingFiles.Count() ) { // recalculate the rest of the install progress based on the new install graph. numberOfPackagesToInstall = installGraph.Count(); numberOfPackagesToDownload = missingFiles.Count(); eachTaskIsWorth = (1.0 - overallProgress)/(numberOfPackagesToInstall + numberOfPackagesToDownload); } if (missingFiles.Any()) { // we've got some packages to install that don't have files. foreach (var p in missingFiles.Where(p => !p.PackageSessionData.HasRequestedDownload)) { PackageManagerMessages.Invoke.RequireRemoteFile(p.CanonicalName, p.InternalPackageData.RemoteLocations , PackageManagerSettings.CoAppCacheDirectory, false); p.PackageSessionData.HasRequestedDownload = true; } } else { if( pretend == true ) { // we can just return a bunch of found-package messages, since we're not going to be // actually installing anything, and everything we needed is downloaded. foreach (var p in installGraph) { PackageManagerMessages.Invoke.PackageInformation(p, Enumerable.Empty()); } return; } var failed = false; // no missing files? Check // complete install graph? Check foreach (var p in installGraph) { var pkg = p; // seems like a good time to check if we're supposed to bail... if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("install-package"); return; } var validLocation = package.PackageSessionData.LocalValidatedLocation; try { if (!pkg.IsInstalled) { if (string.IsNullOrEmpty(validLocation)) { // can't find a valid location PackageManagerMessages.Invoke.FailedPackageInstall(pkg.CanonicalName, pkg.InternalPackageData.LocalLocation, "Can not find local valid package"); pkg.PackageSessionData.PackageFailedInstall = true; } else { var lastProgress = 0; // GS01: We should put a softer lock here to keep the client aware that packages // are being installed on other threads... lock (typeof (MSIBase)) { if (EngineService.DoesTheServiceNeedARestart) { // something has changed where we need restart the service before we can continue. // and the one place we don't wanna be when we issue a shutdown in in Install :) ... EngineService.RestartService(); PackageManagerMessages.Invoke.OperationCancelled("install-package"); return; } pkg.Install(percentage => { overallProgress += ((percentage - lastProgress) *eachTaskIsWorth)/100; lastProgress = percentage; PackageManagerMessages.Invoke.InstallingPackageProgress(pkg.CanonicalName, percentage, (int)(overallProgress*100)); }); } overallProgress += ((100 - lastProgress)*eachTaskIsWorth)/100; PackageManagerMessages.Invoke.InstallingPackageProgress(pkg.CanonicalName, 100,(int)(overallProgress*100)); PackageManagerMessages.Invoke.InstalledPackage(pkg.CanonicalName); } } } catch (Exception e ) /* (PackageInstallFailedException pife) */ { Logger.Error("FAILED INSTALL"); Logger.Error(e); PackageManagerMessages.Invoke.FailedPackageInstall(pkg.CanonicalName, validLocation, "Package failed to install."); pkg.PackageSessionData.PackageFailedInstall = true; if (!pkg.PackageSessionData.AllowedToSupercede) { throw new OperationCompletedBeforeResultException(); // user specified packge as critical. } failed = true; break; } } if (!failed) { // W00T ... We did it! // check for restart required... if (EngineService.DoesTheServiceNeedARestart) { // something has changed where we need restart the service before we can continue. // and the one place we don't wanna be when we issue a shutdown in in Install :) ... EngineService.RestartService(); PackageManagerMessages.Invoke.OperationCancelled("install-package"); return; } return; } // otherwise, let's run it thru again. maybe it'll come together. } //---------------------------------------------------------------------------- // wait until either the manualResetEvent is set, but check every second or so // to see if the client has cancelled the operation. while (!manualResetEvent.WaitOne(500)) { if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("install-package"); return; } // we can also use this opportunity to update progress on any outstanding download tasks. overallProgress += missingFiles.Sum(missingFile => ((missingFile.PackageSessionData.DownloadProgressDelta*eachTaskIsWorth)/100)); } } while (true); } catch (OperationCompletedBeforeResultException) { // can't continue with options given. return; } finally { // remove manualResetEvent from the mre list lock (manualResetEvents) { manualResetEvents.Remove(manualResetEvent); } } } }, TaskCreationOptions.AttachedToParent) Link To Source File
_toolkit_deprecated NewPackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } try { // it takes a non-trivial amount of time to lookup a package by its name. // so, we're going to cache the package in the session. // of course if there isn't one, (because we're downloading soemthing we don't know what it's actualy canonical name is) // we don't want to try looking up each time again, since that's the worst-case-scenario, we have to // cache the fact that we have cached nothing. // /facepalm. Package package; var cachedPackageName = SessionCache.Value["cached-the-lookup" + canonicalName]; if( cachedPackageName == null ) { SessionCache.Value["cached-the-lookup" + canonicalName] = "yes"; package = GetSinglePackage(canonicalName, "download-progress", true); if (package != null) { SessionCache.Value[canonicalName] = package; } } else { package = SessionCache.Value[ canonicalName]; } if (package != null) { package.PackageSessionData.DownloadProgress = Math.Max(package.PackageSessionData.DownloadProgress, downloadProgress.GetValueOrDefault()); } } catch { // suppress any exceptions... we just don't care! } SessionCache.Value["busy" + canonicalName] = null; }, TaskCreationOptions.AttachedToParent) Link To Source File
_toolkit_deprecated NewPackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("list-feeds"); return; } var canFilterSession = PackageManagerSession.Invoke.CheckForPermission(PermissionPolicy.EditSessionFeeds); var canFilterSystem = PackageManagerSession.Invoke.CheckForPermission(PermissionPolicy.EditSystemFeeds); var activeSessionFeeds = SessionCache.Value.SessionValues; var activeSystemFeeds = Cache.Value.Values; var x = from feedLocation in SystemFeedLocations let theFeed = activeSystemFeeds.Where(each => each.IsLocationMatch(feedLocation)).FirstOrDefault() let validated = theFeed != null select new { feed = feedLocation, LastScanned = validated ? theFeed.LastScanned : DateTime.FromFileTime(0), session = false, suppressed = canFilterSystem && BlockedScanLocations.Contains(feedLocation), validated, }; var y = from feedLocation in SessionFeedLocations let theFeed = activeSessionFeeds.Where(each => each.IsLocationMatch(feedLocation)).FirstOrDefault() let validated = theFeed != null select new { feed = feedLocation, LastScanned = validated ? theFeed.LastScanned : DateTime.FromFileTime(0), session = true, suppressed = canFilterSession && BlockedScanLocations.Contains(feedLocation), validated, }; var results = x.Union(y); // paginate the results if (index.HasValue) { results = results.Skip(index.Value); } if (maxResults.HasValue) { results = results.Take(maxResults.Value); } if (results.Any()) { foreach (var f in results) { PackageManagerMessages.Invoke.FeedDetails(f.feed, f.LastScanned, f.session, f.suppressed, f.validated); } } else { PackageManagerMessages.Invoke.NoFeedsFound(); } }, TaskCreationOptions.AttachedToParent) Link To Source File
_toolkit_deprecated NewPackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("add-feed"); return; } if (session ?? false) { // new feed is a session feed // session feed specfied if (!PackageManagerSession.Invoke.CheckForPermission(PermissionPolicy.EditSessionFeeds)) { PackageManagerMessages.Invoke.PermissionRequired("EditSessionFeeds"); return; } // check if it is already a system feed if (SystemFeedLocations.Contains(location)) { PackageManagerMessages.Invoke.Warning("add-feed", "location", "location '{0}' is already a system feed".format(location)); return; } if (SessionFeedLocations.Contains(location)) { PackageManagerMessages.Invoke.Warning("add-feed", "location", "location '{0}' is already a session feed".format(location)); return; } AddSessionFeed(location); PackageManagerMessages.Invoke.FeedAdded(location); // add feed to the session feeds. PackageFeed.GetPackageFeedFromLocation(location).ContinueWith(antecedent => { var foundFeed = antecedent.Result; if (foundFeed != null) { if (foundFeed != SessionPackageFeed.Instance || foundFeed != InstalledPackageFeed.Instance ) { SessionCache.Value[location] = foundFeed; } } else { PackageManagerMessages.Invoke.Error("add-feed", "location", "failed to recognize location '{0}' as a valid package feed".format(location)); LogMessage("Feed {0} was unable to load.", location); } }, TaskContinuationOptions.AttachedToParent); } else { // new feed is a system feed if (!PackageManagerSession.Invoke.CheckForPermission(PermissionPolicy.EditSystemFeeds)) { PackageManagerMessages.Invoke.PermissionRequired("EditSystemFeeds"); return; } if (SystemFeedLocations.Contains(location)) { PackageManagerMessages.Invoke.Warning("add-feed", "location", "location '{0}' is already a system feed".format(location)); return; } AddSystemFeed(location); PackageManagerMessages.Invoke.FeedAdded(location); // add feed to the system feeds. PackageFeed.GetPackageFeedFromLocation(location).ContinueWith(antecedent => { var foundFeed = antecedent.Result; if (foundFeed != null) { if (foundFeed != SessionPackageFeed.Instance || foundFeed != InstalledPackageFeed.Instance) { Cache.Value[location] = foundFeed; } } else { PackageManagerMessages.Invoke.Error("add-feed", "location", "failed to recognize location '{0}' as a valid package feed".format(location)); LogMessage("Feed {0} was unable to load.", location); } }, TaskContinuationOptions.AttachedToParent); } }, TaskCreationOptions.AttachedToParent) Link To Source File
_toolkit_deprecated NewPackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("verify-signature"); return; } if (string.IsNullOrEmpty(filename)) { PackageManagerMessages.Invoke.Error("verify-signature", "filename", "parameter 'filename' is required to verify a file"); return; } var location = PackageManagerSession.Invoke.GetCanonicalizedPath(filename); if (!File.Exists(location)) { PackageManagerMessages.Invoke.FileNotFound(location); return; } var r = Verifier.HasValidSignature(location); if (r) { PackageManagerMessages.Invoke.SignatureValidation(location, r, Verifier.GetPublisherInformation(location)["PublisherName"]); } else { PackageManagerMessages.Invoke.SignatureValidation(location, false, null); } }, TaskCreationOptions.AttachedToParent) Link To Source File
_toolkit_deprecated NewPackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("set-package"); return; } var package = GetSinglePackage(canonicalName, "set-package"); if (package == null) { PackageManagerMessages.Invoke.UnknownPackage(canonicalName); return; } if (!package.IsInstalled) { PackageManagerMessages.Invoke.Error("set-package", "canonical-name", "package '{0}' is not installed.".format(canonicalName)); return; } // seems like a good time to check if we're supposed to bail... if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("set-package"); return; } if (true == active) { if (!PackageManagerSession.Invoke.CheckForPermission(PermissionPolicy.ChangeActivePackage)) { PackageManagerMessages.Invoke.PermissionRequired("ChangeActivePackage"); } else { package.SetPackageCurrent(); } } if (false == active) { if (!PackageManagerSession.Invoke.CheckForPermission(PermissionPolicy.ChangeActivePackage)) { PackageManagerMessages.Invoke.PermissionRequired("ChangeActivePackage"); } else { SearchForInstalledPackages(package.Name, null, package.Architecture, package.PublicKeyToken).HighestPackages().FirstOrDefault(). SetPackageCurrent(); } } if (true == required) { if (!PackageManagerSession.Invoke.CheckForPermission(PermissionPolicy.ChangeRequiredState)) { PackageManagerMessages.Invoke.PermissionRequired("ChangeRequiredState"); } else { package.IsRequired = true; } } if (false == required) { if (!PackageManagerSession.Invoke.CheckForPermission(PermissionPolicy.ChangeRequiredState)) { PackageManagerMessages.Invoke.PermissionRequired("ChangeRequiredState"); } else { package.IsRequired = false; } } if (true == blocked) { if (!PackageManagerSession.Invoke.CheckForPermission(PermissionPolicy.ChangeBlockedState)) { PackageManagerMessages.Invoke.PermissionRequired("ChangeBlockedState"); } else { package.IsBlocked = true; } } if (false == blocked) { if (!PackageManagerSession.Invoke.CheckForPermission(PermissionPolicy.ChangeBlockedState)) { PackageManagerMessages.Invoke.PermissionRequired("ChangeBlockedState"); } else { package.IsBlocked = false; } } PackageManagerMessages.Invoke.PackageInformation(package, Enumerable.Empty()); }, TaskCreationOptions.AttachedToParent) Link To Source File
_toolkit_deprecated NewPackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("remove-package"); return; } if (!PackageManagerSession.Invoke.CheckForPermission(PermissionPolicy.RemovePackage)) { PackageManagerMessages.Invoke.PermissionRequired("RemovePackage"); return; } var package = GetSinglePackage(canonicalName, "remove-package"); if (package == null) { PackageManagerMessages.Invoke.UnknownPackage(canonicalName); return; } if (package.Name.Equals( "coapp.toolkit", StringComparison.CurrentCultureIgnoreCase ) && package.PublicKeyToken.Equals("820d50196d4e8857") && package.IsActive ) { PackageManagerMessages.Invoke.Error("remove-package", "canonical-name", "Active CoApp Engine may not be removed"); return; } if (!package.IsInstalled) { PackageManagerMessages.Invoke.Error("remove-package", "canonical-name", "package '{0}' is not installed.".format(canonicalName)); return; } if (package.IsBlocked) { PackageManagerMessages.Invoke.PackageBlocked(canonicalName); return; } if (true != force) { UpdateIsRequestedFlags(); if (package.PackageSessionData.IsDependency) { PackageManagerMessages.Invoke.FailedPackageRemoval(canonicalName, "Package '{0}' is a required dependency of another package.".format(canonicalName)); return; } } // seems like a good time to check if we're supposed to bail... if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("remove-package"); return; } try { package.Remove((percentage) => PackageManagerMessages.Invoke.RemovingPackageProgress(package.CanonicalName, percentage)); PackageManagerMessages.Invoke.RemovingPackageProgress(canonicalName, 100); PackageManagerMessages.Invoke.RemovedPackage(canonicalName); } catch (OperationCompletedBeforeResultException e) { PackageManagerMessages.Invoke.FailedPackageRemoval(canonicalName, e.Message); return; } }, TaskCreationOptions.AttachedToParent) Link To Source File
_toolkit_deprecated NewPackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("unable-to-acquire"); return; } if (canonicalName.IsNullOrEmpty()) { PackageManagerMessages.Invoke.Error("unable-to-acquire", "canonical-name", "canonical-name is required."); return; } // if there is a continuation task for the canonical name that goes along with this, // we should continue with that task, and get the heck out of here. // var package = GetSinglePackage(canonicalName, null); if (package != null) { package.PackageSessionData.CouldNotDownload = true; } var continuationTask = SessionCache>.Value[canonicalName]; SessionCache>.Value.Clear(canonicalName); Updated(); // notify threads that we're not going to be able to get that file. if (continuationTask != null) { var state = continuationTask.AsyncState as RequestRemoteFileState; if (state != null) { state.LocalLocation = null; } // the task can run, continuationTask.Start(); return; } }, TaskCreationOptions.AttachedToParent) Link To Source File
_toolkit_deprecated NewPackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } if (string.IsNullOrEmpty(localLocation)) { PackageManagerMessages.Invoke.Error("recognize-file", "local-location", "parameter 'local-location' is required to recognize a file"); return; } if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("recognize-file"); return; } var location = PackageManagerSession.Invoke.GetCanonicalizedPath(localLocation); if (location.StartsWith(@"//")) { // a local unc path was passed. This isn't allowed--we need a file on a local volume that // the user has access to. PackageManagerMessages.Invoke.Error("recognize-file", "local-location", "local-location '{0}' appears to be a file on a remote server('{1}') . Recognized files must be local".format(localLocation, location)); return; } if (!File.Exists(location)) { PackageManagerMessages.Invoke.FileNotFound(location); return; } // if there is a continuation task for the canonical name that goes along with this, // we should continue with that task, and get the heck out of here. // if (!canonicalName.IsNullOrEmpty()) { var continuationTask = SessionCache>.Value[canonicalName]; SessionCache>.Value.Clear(canonicalName); if (continuationTask != null) { var state = continuationTask.AsyncState as RequestRemoteFileState; if (state != null) { state.LocalLocation = localLocation; } continuationTask.Start(); return; } } // otherwise, we'll call the recognizer Recognizer.Recognize(location).ContinueWith(antecedent => { if (antecedent.IsFaulted) { PackageManagerMessages.Invoke.FileNotRecognized(location, "Unexpected error recognizing file."); return; } if (antecedent.Result.IsPackageFile) { var package = Package.GetPackageFromFilename(location); // mark it download 100% package.PackageSessionData.DownloadProgress = 100; SessionPackageFeed.Instance.Add(package); PackageManagerMessages.Invoke.PackageInformation(package, Enumerable.Empty()); PackageManagerMessages.Invoke.Recognized(localLocation); return; } if (antecedent.Result.IsPackageFeed) { PackageManagerMessages.Invoke.FeedAdded(location); PackageManagerMessages.Invoke.Recognized(location); } // if this isn't a package file, then there is something odd going on here. // we don't accept non-package files willy-nilly. PackageManagerMessages.Invoke.FileNotRecognized(location, "File isn't a package, and doesn't appear to have been requested. "); return; }, TaskContinuationOptions.AttachedToParent); }, TaskCreationOptions.AttachedToParent) Link To Source File
_toolkit_deprecated NewPackageManager.cs Task.Factory.StartNew(() => { if (messages != null) { messages.Register(); } if (CancellationRequested) { PackageManagerMessages.Invoke.OperationCancelled("suppress-feed"); return; } var suppressedFeeds = SessionCache>.Value["suppressed-feeds"] ?? new List(); lock (suppressedFeeds) { if (!suppressedFeeds.Contains(location)) { suppressedFeeds.Add(location); SessionCache>.Value["suppressed-feeds"] = suppressedFeeds; } } PackageManagerMessages.Invoke.FeedSuppressed(location); }, TaskCreationOptions.AttachedToParent) Link To Source File
_toolkit_deprecated PackageCollectionExtensions.cs Task.Factory.StartNew(() => { }) Link To Source File
_toolkit_deprecated Session.cs Task.Factory.StartNew(() => { new PackageManagerMessages { RequestId = requestMessage["rqid"], }.Extend(_messages).Register(); var policyName = requestMessage["name"].ToString(); var policy = PermissionPolicy.AllPolicies.Where(each => each.Name.Equals(policyName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault(); if( policy == null ) { SendMessageArgumentError("get-policy", "name", "policy '{0}' not found".format(policyName)); return; } var msg = new UrlEncodedMessage("policy") { { "name" , policy.Name }, { "description" , policy.Description}, }; // msg.AddCollection("sids",policy.Sids); msg.AddCollection("accounts", policy.Accounts); WriteAsync(msg); }) Link To Source File
_toolkit_deprecated Session.cs Task.Factory.StartNew(() => { new PackageManagerMessages { RequestId = requestMessage["rqid"], }.Extend(_messages).Register(); if (!_packageManagerSession.CheckForPermission(PermissionPolicy.ModifyPolicy)) { PackageManagerMessages.Invoke.PermissionRequired("ModifyPolicy"); return; } var policyName = requestMessage["name"].ToString(); var policy = PermissionPolicy.AllPolicies.Where(each => each.Name.Equals(policyName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault(); if (policy == null) { SendMessageArgumentError("add-to-policy", "name", "policy '{0}' not found".format(policyName)); return; } try { policy.Add(requestMessage["account"]); } catch { SendMessageArgumentError("add-to-policy", "account", "policy '{0}' could not add account '{1}'".format(policyName, requestMessage["account"])); } }) Link To Source File
_toolkit_deprecated Session.cs Task.Factory.StartNew(() => { new PackageManagerMessages { RequestId = requestMessage["rqid"], }.Extend(_messages).Register(); if (!_packageManagerSession.CheckForPermission(PermissionPolicy.ModifyPolicy)) { PackageManagerMessages.Invoke.PermissionRequired("ModifyPolicy"); return; } var policyName = requestMessage["name"].ToString(); var policy = PermissionPolicy.AllPolicies.Where(each => each.Name.Equals(policyName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault(); if (policy == null) { SendMessageArgumentError("remove-from-policy", "name", "policy '{0}' not found".format(policyName)); return; } try { policy.Remove(requestMessage["account"]); } catch { SendMessageArgumentError("remove-from-policy", "account", "policy '{0}' could not remove account '{1}'".format(policyName, requestMessage["account"])); } }) Link To Source File
_toolkit_deprecated Session.cs Task.Factory.StartNew(() => { // at this point the only thing we are monitoring is the InstalledPackagesFeed. new PackageManagerMessages { RequestId = requestMessage["rqid"], }.Extend(_messages).Register(); var percent = 0; do { Thread.Sleep(10); var p = InstalledPackageFeed.Instance.Progress; if( p > percent) { percent =p ; WriteAsync(new UrlEncodedMessage("engine-status") { { "percent-complete", percent }, }); } } while (percent < 100); }) Link To Source File
_toolkit_deprecated Rehash.cs // signal rehash to proceed. Task.Factory.StartNew(() => { Thread.Sleep(1000); Logger.Message("Rehash: Triggering Global Event"); Kernel32.SetEvent(_globalResetEvent); Thread.Sleep(1000); // give everyone a chance to wake up and do their job Kernel32.ResetEvent(_globalResetEvent); }) Link To Source File
NGauge TaskInternals.cs Task.Factory.StartNew(() => { }) Link To Source File
NGauge TreeTraversing.cs Task.Factory.StartNew(() => DoTree(tree.Left, action)) Link To Source File
NGauge TreeTraversing.cs Task.Factory.StartNew(() => DoTree(tree.Right, action)) Link To Source File
TweetAndPub HistoricalTweetStream.cs Task.Factory.StartNew(Start) Link To Source File
TweetAndPub LiveTweetStream.cs Task.Factory.StartNew(() => Try.Execute(Start, OnError)) Link To Source File
curiosity-common PluralizationTests.cs Task.Factory.StartNew(() => Pluralization.Add(resource)) Link To Source File
RottenTomatoes.NET Movie.cs Task.Factory.StartNew(() => { LoadUnabridged(); OnLoadUnabridgedCompleted(); }) Link To Source File
RottenTomatoes.NET Movie.cs Task.Factory.StartNew(() => { LoadFullCast(); OnLoadFullCastCompleted(); }) Link To Source File
RottenTomatoes.NET Movie.cs Task.Factory.StartNew(() => { LoadTopCriticReviews(); OnLoadReviewsCompleted(); }) Link To Source File
RottenTomatoes.NET Movie.cs Task.Factory.StartNew(() => { LoadTopCriticReviews(); OnLoadReviewsCompleted(); }) Link To Source File
RottenTomatoes.NET MovieSearchResult.cs Task.Factory.StartNew(() => { GetNextPage(); OnGetNextPageCompleted(); }) Link To Source File
il-repack ILRepack.cs Task.Factory.StartNew(() => { INFO("Adding assembly for merge: " + assembly); try { ReaderParameters rp = new ReaderParameters(ReadingMode.Immediate); // read PDB/MDB? if (DebugInfo && (File.Exists(Path.ChangeExtension(assembly, "pdb")) || File.Exists(Path.ChangeExtension(assembly, "mdb")))) { rp.ReadSymbols = true; } AssemblyDefinition mergeAsm; try { mergeAsm = AssemblyDefinition.ReadAssembly(assembly, rp); } catch { // cope with invalid symbol file if (rp.ReadSymbols) { rp.ReadSymbols = false; mergeAsm = AssemblyDefinition.ReadAssembly(assembly, rp); INFO("Failed to load debug information for " + assembly); } else { throw; } } if (!AllowZeroPeKind && (mergeAsm.MainModule.Attributes & ModuleAttributes.ILOnly) == 0) throw new ArgumentException("Failed to load assembly with Zero PeKind: " + assembly); if (rp.ReadSymbols) mergedDebugInfo = true; //if (PrimaryAssemblyDefinition == null) // PrimaryAssemblyDefinition = mergeAsm; //else // OtherAssemblies.Add(mergeAsm); //OtherAssemblies.Add(mergeAsm); readAsms.TryAdd(assembly, mergeAsm); } catch { ERROR("Failed to load assembly " + assembly); throw; } }) Link To Source File
FhvRoomSearch MainViewModel.cs Task.Factory.StartNew(() => DoReloadCourses(url)) Link To Source File
FhvRoomSearch MainViewModel.cs Task.Factory.StartNew(DoSearchAsync) Link To Source File
localtunnel-net-client ForwardedPortLocal.NET40.cs Task.Factory.StartNew(action) Link To Source File
localtunnel-net-client ForwardedPortRemote.NET40.cs Task.Factory.StartNew(action) Link To Source File
localtunnel-net-client KeyboardInteractiveConnectionInfo.NET40.cs Task.Factory.StartNew(action) Link To Source File
localtunnel-net-client PasswordConnectionInfo.NET40.cs Task.Factory.StartNew(action) Link To Source File
localtunnel-net-client SftpClient.NET40.cs Task.Factory.StartNew(action) Link To Source File
localtunnel-net-client Shell.NET40.cs Task.Factory.StartNew(action) Link To Source File
localtunnel-net-client SshCommand.NET40.cs Task.Factory.StartNew(action) Link To Source File
fubumvc AsyncContinueWithBehaviorTests.cs Task.Factory.StartNew(() => { throw new Exception("Failed!"); }) Link To Source File
fubumvc AsyncContinueWithBehaviorTests.cs Task.Factory.StartNew(() => { }) Link To Source File
fubumvc AsyncContinueWithHandlerConventionTester.cs Task.Factory.StartNew(() => { }) Link To Source File
fubumvc ActionInvokersTester.cs Task.Factory.StartNew(() => { }) Link To Source File
OpenSolar SearchResult.cs Task.Factory.StartNew(() => { using (new ReduceAuthenticatedQueryScope()) using (var client = new TwitterClient(this.Account, statusCache)) try { SetValue(() => this.FullUserName, (user ?? (user = client.Users.Get(this.UserName))).FullName); } catch { } }, TaskCreationOptions.LongRunning) Link To Source File
OpenSolar SearchResult.cs Task.Factory.StartNew(() => { using (new ReduceAuthenticatedQueryScope()) using (var client = new TwitterClient(this.Account, statusCache)) try { SetValue(() => this.UserID, (user ?? (user = client.Users.Get(this.UserName))).UserID); } catch { } }, TaskCreationOptions.LongRunning) Link To Source File
OpenSolar CacheWindow.xaml.cs Task.Factory.StartNew(() => { this.IsClearing = true; clearStatuses(); statusCache.Clear(); UriBitmapConverter.Clear(); GC.Collect(); GC.WaitForPendingFinalizers(); Apply(statusCache, clearStatuses); Client.Instance.OnClearCache(); GC.Collect(); this.IsClearing = false; this.Cleared = true; }) Link To Source File
OpenSolar CacheWindow.xaml.cs Task.Factory.StartNew(() => { this.IsClearing = true; statusCache.Clean(); UriBitmapConverter.Clean(); GC.Collect(); GC.WaitForPendingFinalizers(); Apply(statusCache, clearStatuses); Client.Instance.OnClearCache(); GC.Collect(); this.IsClearing = false; this.Cleared = true; }) Link To Source File
OpenSolar AutoCompletion.cs Task.Factory.StartNew(() => { try { var src = this.Source.Freeze(); textBox.Dispatcher.BeginInvoke((Action)(() => { listBox.ItemsSource = src; listBox.SelectedIndex = -1; }), DispatcherPriority.Background); } catch (Exception ex) { App.Log(ex); } }) Link To Source File
OpenSolar AutoCompletion.cs Task.Factory.StartNew(() => { try { var src = this.Source.Select(_ => new { Value = _, Index = selector(_).IndexOf(str, StringComparison.OrdinalIgnoreCase), }).Where(_ => _.Index != -1).OrderBy(_ => _.Index).Select(_ => _.Value).Freeze(); textBox.Dispatcher.BeginInvoke((Action)(() => { if (src.Any()) { listBox.ItemsSource = src; listBox.SelectedIndex = 0; listBox.ScrollIntoView(listBox.Items[listBox.SelectedIndex]); } else listBox.SelectedIndex = -1; }), DispatcherPriority.Background); } catch (Exception ex) { App.Log(ex); } }) Link To Source File
OpenSolar AutoCompletion.cs Task.Factory.StartNew(() => { try { var src = this.Source.Freeze(); if (!src.Any()) return; textBox.Dispatcher.BeginInvoke((Action)(() => { var p = textBox.GetRectFromCharacterIndex(start); listBox.SelectedIndex = -1; listBox.ItemsSource = src; popup.PlacementTarget = textBox; popup.PlacementRectangle = new Rect(p.X + this.OffsetX, p.Y, p.Width, p.Height); popup.IsOpen = true; }), DispatcherPriority.Background); } catch (Exception ex) { App.Log(ex); } }) Link To Source File
OpenSolar ThumbnailedUri.cs Task.Factory.StartNew(() => { using (new ProgressBlock("サムネイルを解決しています...")) try { this.Thumbnail = getThumbnail(this.Original); } catch (Exception ex) { App.Log(ex); App.Current.Dispatcher.Invoke((Action)(() => MessageBoxEx.Show(ex.ToString(), ex.GetType().FullName, MessageBoxButton.OK, MessageBoxImage.Error))); } }) Link To Source File
OpenSolar Client.cs Task.Factory.StartNew(() => { IEnumerable list; lock (updateTimes) list = updateTimes.Keys.Freeze(); list.Where(_ => { lock (updateTimes) return updateTimes.ContainsKey(_) && updateTimes[_]++ > _.Interval.TotalSeconds && (DateTime.Now - _.LastUpdate).TotalSeconds > 1; }) .Run(_ => UpdateInternal(EnumerableEx.Wrap(_))); }) Link To Source File
OpenSolar Client.cs Task.Factory.StartNew(() => { try { using (new TwitterClient(account, this.StatusCache)) AppendStatus(status.Retweet(), true); } catch (Exception ex) { OnThrowError(null, ex); } }) Link To Source File
OpenSolar Client.cs Task.Factory.StartNew(() => { var past = status.Favorited; try { using (new TwitterClient(account, this.StatusCache)) { if (status.Favorited) status.Unfavorite(); else status.Favorite(); } } catch (Exception ex) { status.Favorited = past; OnThrowError(null, ex); } }) Link To Source File
OpenSolar Client.cs Task.Factory.StartNew(() => { try { using (new TwitterClient(status.Account, this.StatusCache)) RemoveStatus(status.Destroy()); } catch (Exception ex) { OnThrowError(null, ex); } }) Link To Source File
OpenSolar Client.cs Task.Factory.StartNew(() => UpdateInternal(category == null ? null : EnumerableEx.Wrap(category))) Link To Source File
OpenSolar Client.cs Task.Factory.StartNew(() => UpdateInternal(category)) Link To Source File
OpenSolar Client.cs Task.Factory.StartNew(() => { var usingAccounts = category.Filter.Sources.Select(_ => _.Account) .Distinct() .Freeze(); var hasAll = usingAccounts.Contains(0); RequestingNewPage.DispatchEvent(this, new EventArgs(category)); try { foreach (var i in hasAll ? this.Accounts : this.Accounts.Where(_ => usingAccounts.Contains(_.UserID))) using (var client = new TwitterClient(i, this.StatusCache)) try { category.RequestNewPage(client); } catch (WebException) { } } catch (Exception ex) { OnThrowWarning(category, ex); RequestedNewPage.DispatchEvent(this, new EventArgs(category)); return false; } RequestedNewPage.DispatchEvent(this, new EventArgs(category)); return true; }) Link To Source File
OpenSolar Client.cs Task.Factory.StartNew(() => { foreach (var i in this.Groups.SelectMany()) i.ClearStatuses(); }) Link To Source File
OpenSolar Client.cs Task.Factory.StartNew(() => { foreach (var i in this.Groups.SelectMany()) i.ApplyFilter(); }) Link To Source File
OpenSolar AuthenticateWindow.xaml.cs Task.Factory.StartNew(() => { try { this.IsLoading = true; Process.Start(this.Authorization.GetAuthorizationUri().AbsoluteUri); } catch (Exception ex) { RequestError.DispatchEvent(this, new EventArgs(App.Log(ex))); } finally { this.IsLoading = false; } }) Link To Source File
OpenSolar AuthenticateWindow.xaml.cs Task.Factory.StartNew(() => { try { this.IsLoading = true; this.Authorization.Authenticate(this.PIN); RequestClose.DispatchEvent(this, new EventArgs(true)); } catch (Exception ex) { RequestError.DispatchEvent(this, new EventArgs(App.Log(ex))); } finally { this.IsLoading = false; } }) Link To Source File
OpenSolar LinkConverter.cs Task.Factory.StartNew(() => { lock (ResolvedUriCache) if (ResolvedUriCache.ContainsKey(uri)) dispatcher.BeginInvoke(setLink, DispatcherPriority.Background, ResolvedUriCache[uri]); else { var resolver = Client.Instance.UrlExpanders.FirstOrDefault(_ => _.GetVariable("IsShort")(uri)); if (resolver != null) using (new ProgressBlock("短縮 URL を解決しています...")) lock (uri.AbsoluteUri) try { var rt = (string)resolver.GetVariable("Expand")(uri); if (rt == null) return; dispatcher.BeginInvoke(setLink, DispatcherPriority.Background, ResolvedUriCache[uri] = rt); if (ResolvedUriCache.Count > MaxResolvedUriCache) ResolvedUriCache.RemoveAt(0); } catch (Exception ex) { App.Log(ex); } } }, TaskCreationOptions.LongRunning) Link To Source File
OpenSolar FollowManagerWindow.xaml.cs Task.Factory.StartNew(() => { try { using (var client = new TwitterClient(cp.Accounts.Single(), cp.StatusCache)) client.Friendships.Create(_.User.UserID); } catch (ContentedWebException ex) { RequestMessageBox.DispatchEvent(this, new EventArgs>(window => MessageBoxEx.Show(window, ex.Message, "送信中にエラーが発生しました", MessageBoxButton.OK, MessageBoxImage.Warning))); } }) Link To Source File
OpenSolar FollowManagerWindow.xaml.cs Task.Factory.StartNew(() => { try { using (var client = new TwitterClient(cp.Accounts.Single(), cp.StatusCache)) client.Friendships.Destroy(_.User.UserID); } catch (ContentedWebException ex) { RequestMessageBox.DispatchEvent(this, new EventArgs>(window => MessageBoxEx.Show(window, ex.Message, "送信中にエラーが発生しました", MessageBoxButton.OK, MessageBoxImage.Warning))); } }) Link To Source File
OpenSolar FollowManagerWindow.xaml.cs Task.Factory.StartNew(() => { try { using (var client = new TwitterClient(cp.Accounts.Single(), cp.StatusCache)) client.Blocks.Create(_.User.UserID); } catch (ContentedWebException ex) { RequestMessageBox.DispatchEvent(this, new EventArgs>(window => MessageBoxEx.Show(window, ex.Message, "送信中にエラーが発生しました", MessageBoxButton.OK, MessageBoxImage.Warning))); } }) Link To Source File
OpenSolar FollowManagerWindow.xaml.cs Task.Factory.StartNew(() => { try { using (var client = new TwitterClient(cp.Accounts.Single(), cp.StatusCache)) client.Blocks.Destroy(_.UserID); } catch (ContentedWebException ex) { RequestMessageBox.DispatchEvent(this, new EventArgs>(window => MessageBoxEx.Show(window, ex.Message, "送信中にエラーが発生しました", MessageBoxButton.OK, MessageBoxImage.Warning))); } }) Link To Source File
OpenSolar FollowManagerWindow.xaml.cs Task.Factory.StartNew(() => { this.IsLoadingBlocks = true; this.HasBlocksError = false; try { using (new ReduceAuthenticatedQueryScope()) foreach (var i in cp.Accounts) using (var client = new TwitterClient(i, cp.StatusCache)) { var blocks = client.Blocks.Blocking().Freeze(); this.Blocks.AddRangeAsync(blocks.Select(_ => _.User)); } } catch (Exception ex) { this.HasBlocksError = false; this.BlocksError = ex; } this.IsLoadingBlocks = false; }) Link To Source File
OpenSolar FollowManagerWindow.xaml.cs Task.Factory.StartNew(() => { this.IsLoadingFollows = true; this.HasFollowsError = false; try { using (new ReduceAuthenticatedQueryScope()) foreach (var i in cp.Accounts) using (var client = new TwitterClient(i, cp.StatusCache)) { var followers = client.Statuses.Followers().SelectMany().Freeze(); var friends = client.Statuses.Friends().SelectMany().Freeze(); var eq = new InstantEqualityComparer(_ => _.UserID); this.Follows.AddRangeAsync(followers.Intersect(friends, eq).Select(_ => new Follow(FollowState.TwoWay, _.User))); this.Follows.AddRangeAsync(friends.Except(followers, eq).Select(_ => new Follow(FollowState.Following, _.User))); this.Follows.AddRangeAsync(followers.Except(friends, eq).Select(_ => new Follow(FollowState.Follower, _.User))); } } catch (Exception ex) { this.HasFollowsError = true; this.FollowsError = ex; } this.IsLoadingFollows = false; }) Link To Source File
OpenSolar QueryResultWindow.xaml.cs Task.Factory.StartNew(() => { try { using (new TwitterClient(cp.Accounts.First(), cp.StatusCache)) if (this.IsUserFollowing) this.User.Follow(); else this.User.Unfollow(); } catch (ContentedWebException ex) { RequestMessageBox.DispatchEvent(this, new EventArgs>(window => MessageBoxEx.Show(window, ex.Message, "送信中にエラーが発生しました", MessageBoxButton.OK, MessageBoxImage.Warning))); } }) Link To Source File
OpenSolar QueryResultWindow.xaml.cs Task.Factory.StartNew(() => { try { using (var client = new TwitterClient(cp.Accounts.First(), cp.StatusCache)) if (this.IsUserBlocking) client.Blocks.Create(this.User.UserID); else client.Blocks.Destroy(this.User.UserID); } catch (ContentedWebException ex) { RequestMessageBox.DispatchEvent(this, new EventArgs>(window => MessageBoxEx.Show(window, ex.Message, "送信中にエラーが発生しました", MessageBoxButton.OK, MessageBoxImage.Warning))); } }) Link To Source File
OpenSolar QueryResultWindow.xaml.cs Task.Factory.StartNew(() => { try { using (var client = new TwitterClient(cp.Accounts.First(), cp.StatusCache)) client.ReportSpam(this.User.UserID); } catch (ContentedWebException ex) { RequestMessageBox.DispatchEvent(this, new EventArgs>(window => MessageBoxEx.Show(window, ex.Message, "送信中にエラーが発生しました", MessageBoxButton.OK, MessageBoxImage.Warning))); } }) Link To Source File
OpenSolar QueryResultWindow.xaml.cs Task.Factory.StartNew(() => { this.UserErrorText = null; try { using (new ReduceAuthenticatedQueryScope()) using (var client = new TwitterClient(cp.Accounts.First(), cp.StatusCache)) { this.IsLoadingUser = true; if (this.User == null) this.User = client.Users.Get(setUserName); ((UserFilterSource)this.Source).UserID = this.User.UserID; this.HasUserLocation = !string.IsNullOrEmpty(this.User.Location); this.HasUserWebSite = this.User.WebSite != null; this.HasUserDescription = !string.IsNullOrEmpty(this.User.Description); this.UserDescription = this.HasUserDescription ? this.User.Description.Replace("/r", "...").TakeWhile(_ => _ != '/n').Join("") : null; this.IsUserFollowing = client.Friendships.Get(cp.Accounts.First().Name, this.User.Name).SourceFollowingTarget; this.IsUserBlocking = client.Blocks.Exists(this.User.Name); this.IsLoadingUser = false; } } catch (Exception ex) { this.UserErrorText = App.Log(ex).Message; } }) Link To Source File
OpenSolar App.xaml.cs Task.Factory.StartNew(() => { try { if (!UpdateInfo.Load() .Update(_ => MessageBoxEx.Show(App.Current.MainWindow, "Solar " + _.Version + " を取得しました。/r/nSolar を終了すると自動的に新しいバージョンが起動されます。/r/n今すぐ新しいバージョンを起動しますか?", "アップデート", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) && !isAutomatic) App.Current.Dispatcher.BeginInvoke((Action)(() => MessageBoxEx.Show(App.Current.MainWindow, "新しいバージョンは見つかりませんでした。", "アップデート", MessageBoxButton.OK, MessageBoxImage.Information)), DispatcherPriority.Background); } catch (WebException ex) { App.Log(ex); if (!isAutomatic) App.Current.Dispatcher.BeginInvoke((Action)(() => MessageBoxEx.Show(App.Current.MainWindow, ex.Message, ex.GetType().FullName, MessageBoxButton.OK, MessageBoxImage.Warning)), DispatcherPriority.Background); } }) Link To Source File
OpenSolar MainWindow.xaml.cs Task.Factory.StartNew(() => { using (var s = new SoundPlayer(e.Value1.NotifySound)) s.PlaySync(); }) Link To Source File
OpenSolar MainWindow.xaml.cs Task.Factory.StartNew(() => { if (Settings.Default.Post.AutoSwitchAccount) this.PostAccount = this.Accounts.FirstOrDefault(a => a.InternalAccount.Equals(_.Account)); this.PostText = " RT @" + _.UserName + ": " + _.Text; RequestFocusStartPostTextBox.DispatchEvent(this, EventArgs.Empty); }) Link To Source File
OpenSolar MainWindow.xaml.cs Task.Factory.StartNew(() => { this.IsPosting = true; try { this.PostText = this.Model.ShortenUrls(_, this.PostText); } finally { this.IsPosting = false; } }) Link To Source File
OpenSolar MainWindow.xaml.cs Task.Factory.StartNew(() => { try { using (new ReduceAuthenticatedQueryScope()) using (var client = new TwitterClient(this.PostAccount.InternalAccount, this.Model.StatusCache)) this.FollowerNames = client.Statuses.Followers(this.PostAccount.InternalAccount.Name).SelectMany().Select(_ => _.UserName).Freeze(); } catch (Exception ex) { this.FollowerNames = new[] { ex.Message, }; App.Log(ex); } }) Link To Source File
MS-OSM-Querys MainController.cs Task.Factory.StartNew(() => { Task.WaitAll(tasks); continuation(null); _watch.Stop(); _phase = MainControllerStates.Idle; }) Link To Source File
MS-OSM-Querys DBLoader.cs Task.Factory.StartNew(actioB) Link To Source File
MS-OSM-Querys XmlOSMFileLoader.cs Task.Factory.StartNew(() => Read(path,filters)) Link To Source File
CorrugatedIron RiakAsyncClient.cs Task.Factory.StartNew(action) Link To Source File
CorrugatedIron RiakCluster.cs Task.Factory.StartNew(NodeMonitor) Link To Source File
Footloose MessageOriginator.cs Task.Factory.StartNew( x => { // create a new token that combines the internal and external tokens var internalCancellationTokenSource = new CancellationTokenSource(); var internalCancellationToken = internalCancellationTokenSource.Token; using ( var linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(internalCancellationToken, cancellationToken)) { try { var linkedCancellationToken = linkedCancellationTokenSource.Token; var messages = BuildMessages(to, data, linkedCancellationToken); if (messages.RequestMessage != null) SendRequestMessage(messages.RequestMessage, linkedCancellationTokenSource); SendDataMessages(messages.DataMessages, linkedCancellationTokenSource); } catch (OperationCanceledException) { if (internalCancellationToken.IsCancellationRequested) { logger.Error("[Task {0}] Send data message operation to endpoint '{1}' timed out.", Task.CurrentId, to); throw new TimeoutException( string.Format("Send data message operation to endpoint '{0}' timed out.", to)); } else if (cancellationToken.IsCancellationRequested) { logger.Debug( () => string.Format("[Task {0}] Cancelling per user request.", Task.CurrentId)); cancellationToken.ThrowIfCancellationRequested(); } } } }, cancellationToken) Link To Source File
Footloose AmqpConnection.cs Task.Factory.StartNew( () => { try { using (var incomingChannel = connection.CreateModel()) { incomingChannel.ModelShutdown += OnConnectionClosed; incomingChannel.CallbackException += OnExceptionOccured; var consumer = new QueueingBasicConsumer(incomingChannel); var consumerTag = incomingChannel.BasicConsume(ServiceUri.AbsoluteUri, false, consumer); while (true) { if (IsDisposed) break; if(incomingTaskCancellationTokenSource.IsCancellationRequested) { logger.Debug( () => string.Format("Task[{0}] Cancellation of incoming listener requested.", Task.CurrentId)); incomingChannel.BasicCancel(consumerTag); break; } logger.Debug( () => string.Format("Task[{0}] Waiting for incoming messages.", Task.CurrentId)); object itemFromQueue; if (!consumer.Queue.Dequeue(5000, out itemFromQueue)) continue; var message = itemFromQueue as BasicDeliverEventArgs; if (message == null) continue; logger.Debug( () => string.Format("Task[{0}] Handle incoming message.", Task.CurrentId)); OnMessageReceived(message); // acknowledge receipt of the message incomingChannel.BasicAck(message.DeliveryTag, false); } } } catch (OperationInterruptedException exception) { // The consumer was removed, either through // channel or connection closure, or through the // action of IModel.BasicCancel(). logger.ErrorException("Exception occured.", exception); //TODO: handle exception } catch (IOException exception) { // Check why socket was closed logger.ErrorException("Exception occured.", exception); //TODO: handle exception } finally { logger.Debug( () => string.Format("Task[{0}] Exiting incoming message handler.", Task.CurrentId)); } }, incomingTaskCancellationTokenSource.Token) Link To Source File
Programmatically-Speaking-Repository logger.cs Task.Factory.StartNew(() => { var cToken = _cts.Token; for (; ; ) { _lwriter.WriteLine(_buf.Receive()); if (cToken.IsCancellationRequested && _buf.Count == 0) return; } }) Link To Source File
Kata GuruViewModel.cs Task.Factory.StartNew(() => GuruPresentYourSelf(retries)) Link To Source File
Kata GuruViewModel.cs Task.Factory.StartNew(() => GuruWhereAreYou(retries)) Link To Source File
Kata KnowledgeViewModel.cs Task.Factory.StartNew(() => AskAllGurusAQuestion(question, numberOfTimes, askInParallel)) Link To Source File
Kata KnowledgeViewModel.cs Task.Factory.StartNew(() => AskAGuruAQuestion(localGuruViewModel, question)) Link To Source File
Tempest NetworkConnectionProvider.cs Task.Factory.StartNew (() => { #endif this.pkEncryption = this.pkCryptoFactory(); this.publicEncryptionKey = this.pkEncryption.ExportKey (false); #if NET_4 }) Link To Source File
Tempest NetworkConnectionProvider.cs Task.Factory.StartNew (() => { #endif this.authentication = this.pkCryptoFactory(); if (this.authenticationKey == null) this.authenticationKey = this.authentication.ExportKey (true); else this.authentication.ImportKey (this.authenticationKey); this.publicAuthenticationKey = this.authentication.ExportKey (false); if (enabledHashAlgs == null || !enabledHashAlgs.Any()) this.enabledHashAlgorithms.AddRange (this.authentication.SupportedHashAlgs); else // Need to maintain preference order this.enabledHashAlgorithms.AddRange (enabledHashAlgs.Where (a => this.authentication.SupportedHashAlgs.Contains (a))); #if NET_4 }) Link To Source File
RuElect AnalyzeViewModel.cs Task.Factory.StartNew( () => { IsLoading = true; Repository.Initialize(); if (Tcs.IsCancellationRequested) return; IEnumerable regions = Repository.GetRegions(); Action action = () => { Regions = new ObservableCollection(regions.OrderBy(r => r.Name)); }; if (Application.Current != null) Application.Current.Dispatcher.Invoke(action); else action(); }) Link To Source File
RuElect AnalyzeViewModel.cs Task.Factory.StartNew( () => { IsLoading = true; IEnumerable protocols = Repository.GetComissionProtocols(comission); Action action = () => { Protocols = new ObservableCollection(protocols.OrderBy(p => p.Provider.Name)); }; if (Application.Current != null) Application.Current.Dispatcher.Invoke(action); else action(); }) Link To Source File
RuElect KartaitogovViewModel.cs Task.Factory.StartNew( () => { IsLoading = true; Repository.Initialize(); bool isNewProvider; string providerName = String.IsNullOrWhiteSpace(ProviderName) ? DefaultProviderName : ProviderName; ResultProvider provider = Repository.GetOrCreateProvider(providerName, out isNewProvider); var poll = ensurePollCreated(); provider.Poll = poll; if (Tcs.IsCancellationRequested) return; string pageContent = downloadMainPage(); if (Tcs.IsCancellationRequested) return; IDictionary imageFilesMap = parseAndDownloadImages(pageContent); var loader = new KartaitogovWebLoader(pageContent, imageFilesMap, Logger); loadProtocols(loader, provider, isNewProvider); }) Link To Source File
RuElect KartaitogovViewModel.cs Task.Factory.StartNew( () => { if (String.IsNullOrEmpty(ImagesFolder)) { log("You should specify folder for protocol images"); return; } IsLoading = true; string pageContent = downloadMainPage(); if (Tcs.IsCancellationRequested) return; parseAndDownloadImages(pageContent); }) Link To Source File
RuElect RuelectViewModel.cs Task.Factory.StartNew( () => { if (!ensureFileNameSpecified()) return; Repository.Initialize(); if (DownloadCsv) { FileName = downloadAndSaveCsv(); if (String.IsNullOrEmpty(FileName)) return; } var loader = new RuelectCsvLoader(FileName); try { loader.CheckRegions(Repository); log("All regions from csv-file exist in DB"); } catch (InvalidDataException ex) { log(ex.ToString()); //MessageBox.Show(ex.ToString()); } finally { loader.Dispose(); } }, TaskCreationOptions.LongRunning) Link To Source File
RuElect RuelectViewModel.cs Task.Factory.StartNew( () => { if (!ensureFileNameSpecified()) return; IsLoading = true; Repository.Initialize(); if (DownloadCsv) { FileName = downloadAndSaveCsv(); if (String.IsNullOrEmpty(FileName )) return; } bool isNewProvider; string providerName = String.IsNullOrWhiteSpace(ProviderName) ? DefaultProviderName : ProviderName; ResultProvider provider = Repository.GetOrCreateProvider(providerName , out isNewProvider); var poll = ensurePollCreated(); provider.Poll = poll; if (Tcs.IsCancellationRequested) return; var loader = new RuelectCsvLoader(FileName); loadProtocols(loader, provider, isNewProvider); }, TaskCreationOptions.LongRunning) Link To Source File
RuElect App.xaml.cs Task.Factory.StartNew( () => { using (var con = new SqlConnection(m_connectionString)) { try { con.Open(); con.Close(); } catch (Exception ex) { logger.Log("Cannot open DB, please check connection string in Loader.exe.config. Exception: " + ex); } } }) Link To Source File
Filechronization ConnectionManager.cs Task.Factory.StartNew(Read) Link To Source File
Filechronization AsyncConnection.cs Task.Factory.StartNew(ScheduleStreamRead) Link To Source File
Filechronization AsyncConnection.cs Task.Factory.StartNew(FireCallback) Link To Source File
Filechronization TaskManager.cs //TODO: Dodac szeregowanie elementow o tym samym kluczu System.Threading.Tasks.Task.Factory.StartNew(delegate() { if (!task.synchronized) task.foreignTaskID = taskMessage.foreignTaskID; if (task.ProcessMessage(taskMessage.message)) { //tasks.Remove(taskMessage.taskID); //Notification.Diagnostic(this, "Task finished: " + task.ToString()); } }) Link To Source File
Tardis HttpServer.cs Task.Factory.StartNew(() => { while (!this.shutdown) { try { Socket socket = mySocket.Accept(); Task.Factory.StartNew(() => { if (!this.shutdown) { this.ProcessRequest( new HttpSocket(socket)); } }); continue; } catch { Thread.Sleep(100); continue; } } }) Link To Source File
Tardis HttpServer.cs Task.Factory.StartNew(() => { if (!this.shutdown) { this.ProcessRequest( new HttpSocket(socket)); } }) Link To Source File
FTKEYBOARD Kernel.cs Task.Factory.StartNew(() => { try { Stream data = new MemoryStream(e.Data); IPEndPoint endpoint = e.EndPoint; var header = (FTKEYBOARD.Protocol.ProtocolType)data.ReadByte(); switch (header) { // FTK case FTKEYBOARD.Protocol.ProtocolType.OP_FTKHEADER: this.ftProcesser.ProcessPacket(ref data, endpoint); break; default: LogManager.LogDebug("Kernel - OnDataReceived: Unknown Packet from " + endpoint.ToString()); break; } } catch (Exception ee) { LogManager.LogError("Kernel - ReceiveData: " + ee.Message); } }) Link To Source File
GiveCRM GeneratorWindow.xaml.cs Task.Factory.StartNew(() => { Log("Connecting to database..."); db = Database.OpenConnection(connectionString); Log("Connected to database successfully"); }, TaskCreationOptions.LongRunning) Link To Source File
GiveCRM ExcelImportController.cs // Process the file Task.Factory.StartNew(() => ImportAsync(file.FileName, file.InputStream)) Link To Source File
Twiddler TimelineScreen.cs new TaskFactory().StartNew(() => readTweet.MarkAsReadCommand.Execute(null)) Link To Source File
nuget AggregateQuery.cs Task.Factory.StartNew(() => { T current; return new { Empty = !queue.TryPeek(out current), Value = current, Queue = queue, }; }) Link To Source File
nuget ProductUpdateService.cs Task.Factory.StartNew(() => { try { // Find the vsix on the vs gallery VSGalleryEntry nugetVsix = _extensionRepository.CreateQuery() .Where(e => e.VsixID == NuGetVSIXId) .AsEnumerable() .FirstOrDefault(); // Get the current NuGet VSIX version IInstalledExtension installedNuGet = _extensionManager.GetInstalledExtension(NuGetVSIXId); Version installedVersion = installedNuGet.Header.Version; // If we're running an older version then update if (nugetVsix != null && nugetVsix.NonNullVsixVersion > installedVersion) { RaiseUpdateEvent(new ProductUpdateAvailableEventArgs(installedVersion, nugetVsix.NonNullVsixVersion)); } } catch { // Swallow all exceptions. We don't want to take down vs, if the VS extension // gallery happens to be down. } }) Link To Source File
Stateless SequentialActionQueue.cs Task.Factory.StartNew(() => { this.IsActive = true; Action result; while (queue.TryDequeue(out result)) { result(); } this.IsActive = false; }) Link To Source File
NicoCacheDriver NicoCacheDriverForm.cs taskFactory.StartNew(LoadSettings) Link To Source File
NicoCacheDriver NicoCacheDriverForm.cs taskFactory.StartNew(() => { SettingsManager newSmng = new SettingsManager(); newSmng.ConverterMap.Add(typeof(Regex), new FlexibleConverter(regex => regex.ToString(), str => new Regex(str))); settingsLoaded = false; string settingsFilePath = GetSettingsFilePath(); newSmng.Load(settingsFilePath); string usersessionFactory = newSmng.GetItem(SettingsConstants.USERSESSION_FACTORY); smng.SetOrAddNewItem(SettingsConstants.USERSESSION_FACTORY, usersessionFactory); foreach (SettingsItem timerNameItem in smng.GetItems(SettingsConstants.TIMER_NAME)) { string timerName = timerNameItem.Value; string timerIntervalName = string.Format("{0}_{1}", SettingsConstants.TIMER_INTERVAL_PREFIX, timerName); smng.RemoveAll(timerIntervalName); string timerPatternName = string.Format("{0}_{1}", SettingsConstants.TIMER_PATTERN_PREFIX, timerName); smng.RemoveAll(timerPatternName); } smng.RemoveAll(SettingsConstants.TIMER_NAME); foreach (string timerName in newSmng.GetItems(SettingsConstants.TIMER_NAME)) { smng.AddItem(SettingsConstants.TIMER_NAME, timerName); string timerIntervalName = string.Format("{0}_{1}", SettingsConstants.TIMER_INTERVAL_PREFIX, timerName); TimeSpan timerInterval = newSmng.GetItem(timerIntervalName); smng.AddItem(timerIntervalName, timerInterval); string timerPatternName = string.Format("{0}_{1}", SettingsConstants.TIMER_PATTERN_PREFIX, timerName); Regex timerPattern = newSmng.GetItem(timerPatternName); smng.AddItem(timerPatternName, timerPattern); } string userSession = GetUserSession(smng); downloadWorker.SetUserSession(userSession); NicoAccessTimer timer = downloadWorker.Timer; NicoAccessTimer newTimer = timer.DeriveNewTimer(smng); downloadWorker.Timer = newTimer; return userSession; }) Link To Source File
LoLNotes MainForm.cs Task.Factory.StartNew(() => LoadPlayer(ply, plycontrol)) Link To Source File
LoLNotes MainForm.cs Task.Factory.StartNew(() => Recorder.CommitPlayer(plrcontrol.Player)) Link To Source File
LoLNotes MainForm.cs Task.Factory.StartNew(() => Recorder.CommitPlayer(plrcontrol.Player)) Link To Source File
LoLNotes MainForm.cs Task.Factory.StartNew(GetGeneral) Link To Source File
LoLNotes GameStorage.cs Task.Factory.StartNew(() => CommitLobby(lobby)) Link To Source File
LoLNotes GameStorage.cs Task.Factory.StartNew(() => CommitGame(game)) Link To Source File
BeatDancer BeatManager.cs Task.Factory.StartNew(() => { Detect(buffer, ref bs); }) Link To Source File
Maggie.WPF ScrapeKeywordViewModel.cs Task.Factory.StartNew( () => _scrapeService.InitiateKeywordScrape(scrapeOptions)) Link To Source File
Maggie.WPF HarvestStatusViewModel.cs Task.Factory.StartNew(() => _scrapeService.BackgroundScrapePendingPatents(scrapeOptions)) Link To Source File
ILSpy XmlResourceNode.cs Task.Factory.StartNew( () => { try { // cache read XAML because stream will be closed after first read if (xml == null) { using (var reader = new StreamReader(Data)) { xml = reader.ReadToEnd(); } } output.Write(xml); highlighting = HighlightingManager.Instance.GetDefinitionByExtension(".xml"); } catch (Exception ex) { output.Write(ex.ToString()); } return output; }) Link To Source File
ILSpy XamlResourceNode.cs Task.Factory.StartNew( () => { try { // cache read XAML because stream will be closed after first read if (xaml == null) { using (var reader = new StreamReader(Data)) { xaml = reader.ReadToEnd(); } } output.Write(xaml); highlighting = HighlightingManager.Instance.GetDefinitionByExtension(".xml"); } catch (Exception ex) { output.Write(ex.ToString()); } return output; }) Link To Source File
ILSpy BamlResourceEntryNode.cs Task.Factory.StartNew( () => { try { if (LoadBaml(output)) highlighting = HighlightingManager.Instance.GetDefinitionByExtension(".xml"); } catch (Exception ex) { output.Write(ex.ToString()); } return output; }) Link To Source File
SharpDevelop ParserService.cs System.Threading.Tasks.Task.Factory.StartNew( delegate { try { return ParseFile(null, fileContent); } catch (Exception ex) { MessageService.ShowException(ex, "Error during async parse"); return null; } } ) Link To Source File
BinaryAnalysis.Core BootstrapModal.cs Task.Factory.StartNew(Initialize) Link To Source File
InfinityMQ ThreadedBenchmark.cs Task.Factory.StartNew(() => { this.serverReadyEvent.WaitOne(); SetupClient(); this.clientReadyEvent.Set(); MeasureLatency(); this.clientCompletedEvent.Set(); this.serverCompletedEvent.WaitOne(); TeardownClient(); }) Link To Source File
InfinityMQ ThreadedBenchmark.cs Task.Factory.StartNew(() => { SetupServer(); this.serverReadyEvent.Set(); WaitForClient(); this.clientReadyEvent.WaitOne(); MeasureThroughput(); this.serverCompletedEvent.Set(); this.clientCompletedEvent.WaitOne(); TeardownServer(); }) Link To Source File
ironfoundry NatsMessagingProvider.cs Task.Factory.StartNew(Poll) Link To Source File
ironfoundry NatsMessagingProvider.cs Task.Factory.StartNew(MessageProcessor) Link To Source File
ironfoundry NatsMessagingProvider.cs callbackRunnerFactory.StartNew(() => { try { callback(message.Message, message.InboxID); } catch (Exception ex) { log.Error(ex, Resources.NatsMessagingProvider_ExceptionInCallbackForSubscription_Fmt, message.Subject); } }) Link To Source File
iSynaptic.Commons MaybeTests.cs Task.Factory.StartNew(() => { results = value.Value; }) Link To Source File
iSynaptic.Commons MaybeTests.cs Task.Factory.StartNew(() => { results = value.Value; }) Link To Source File
iSynaptic.Commons MaybeTests.cs Task.Factory.StartNew(() => { while (Thread.VolatileRead(ref started) != 1) continue; }) Link To Source File
iSynaptic.Commons MaybeTests.cs Task.Factory.StartNew(() => { while (Thread.VolatileRead(ref ended) != 1) continue; }) Link To Source File
PicasaUploader AlbumsPage.cs Task.Factory.StartNew(() => { LoadAlbums(); ProgressMonitor.CompleteTask(); OnInitializationComplete(); }) Link To Source File
PicasaUploader AlbumsPage.cs Task.Factory.StartNew(() => { ViewModel.CreateAlbumCommand.CreateAlbum(newAlbumModel); ProgressMonitor.CompleteTask(); Initialize(); }) Link To Source File
LessonsLearned VerifyPersonActivity.cs Task.Factory.StartNew(() => Persist(input, accept)) Link To Source File
ViajesDosan.CityTours.Invoices BrowseViewModel.cs Task.Factory. StartNew(() => { PagedEnumerable query = _feesService.ExistingFees(Skip, PageSize); _page = new PagedEnumerable(query.Entities.Select(FeeViewModel.From), query.Total, Skip, PageSize); }) Link To Source File
ViajesDosan.CityTours.Invoices WorkflowStateFactory.cs Task.Factory.StartNew(o) Link To Source File
ViajesDosan.CityTours.Invoices BrowseViewModel.cs Task.Factory. StartNew(() => { PagedEnumerable query = _resellersService.ExistingResellers(Skip, PageSize); _page = new PagedEnumerable( query.Entities.Select(ResellerViewModel.From), query.Total, Skip, PageSize); }) Link To Source File
ViajesDosan.CityTours.Invoices WorkflowStateFactory.cs Task.Factory.StartNew(o) Link To Source File
cityindex Ribbon1.cs Task.Factory.StartNew(() => Login()) Link To Source File
cityindex Ribbon1.cs Task.Factory.StartNew(() => Logout()) Link To Source File
cityindex Ribbon1.cs Task.Factory.StartNew(() => Login()) Link To Source File
cityindex Ribbon1.cs Task.Factory.StartNew(() => Login()) Link To Source File
cityindex Ribbon1.cs Task.Factory.StartNew(() => EditPattern()) Link To Source File
Nova ClientManager.cs Task.Factory.StartNew(() => { var clientMachine = new Machine() { Identity = MachineIdentity.GetCurrentIdentity() }; clientMachine.PrivateEndPoint = Network.GetInternalEndPoint(); // clientMachine.PublicEndPoint will be read off the SenderEndPoint by the Introducer when we send this message var serverMachine = new Machine(); serverMachine.NovaId = novaId; serverMachine.PasswordHash = HashUtil.ComputeHash(password, HashType.SHA512); Network.SendUnconnectedMessage(new RequestIntroducerIntroductionMessage { ClientMachine = clientMachine, ServerMachine = serverMachine }, Config.GetIPEndPoint("IntroducerEndPoint")); }, TaskCreationOptions.AttachedToParent) Link To Source File
MatchRedux DayScan.xaml.cs Task.Factory.StartNew(() => { for (DateTime dt = earliest; dt <= latest; dt = dt.AddDays(1)) { ScanWholeDay(dt, thumbnail); if (_cancelled) { Dispatcher.Invoke((MyDelegate)delegate { cancelButton.IsEnabled = false; working.Content = "Cancelled"; }); break; } } _cancelled = false; }) Link To Source File
MatchRedux FindGaps.xaml.cs Task.Factory.StartNew(() => { StringBuilder sql = new StringBuilder(); sql.AppendLine("insert into gaps (programme_id, service_id, gapstart,gapend)");// VALUES(1234,1,"2007-06-28 03:00","2007-06-28 06:00") using (var data = new ReduxEntities()) { var programmes = (from prog in data.pips_programmes //orderby prog.ServiceId, prog.StartTime select prog).ToList(); programmes = (from prog in programmes orderby prog.service_id, prog.start_gmt select prog).ToList(); pips_programmes prev = null; using (var newdata = new ReduxEntities()) { foreach (var prog in programmes) { if (prev != null && prev.service_id == prog.service_id && prev.end_gmt < prog.start_gmt) { gap gap = new gap { programme_id = prog.id, service_id = prog.service_id, gapstart = prev.end_gmt, gapend = prog.start_gmt }; newdata.gaps.AddObject(gap); Dispatcher.Invoke((MyDelegate)delegate { gapLabel.Content = string.Format("{0}", gap.gapstart); }); } if (prev == null || prog.service_id != prev.service_id || prog.end_gmt > prev.end_gmt) { prev = prog; } } newdata.SaveChanges(); } Dispatcher.Invoke((MyDelegate)delegate { gapGrid.ItemsSource = data.gaps; }); } }) Link To Source File
MatchRedux Progress.xaml.cs Task.Factory.StartNew(action) Link To Source File
MatchRedux DayScan.xaml.cs Task.Factory.StartNew(() => { for (DateTime dt = earliest; dt <= latest; dt = dt.AddDays(1)) { ScanWholeDay(dt); if (_cancelled) { Dispatcher.Invoke((MyDelegate)delegate { cancelButton.IsEnabled = false; working.Content = "Cancelled"; }); break; } } _cancelled = false; }) Link To Source File
MatchRedux FindGaps.xaml.cs Task.Factory.StartNew(() => { StringBuilder sql = new StringBuilder(); sql.AppendLine("insert into gaps (programme_id, service_id, gapstart,gapend)");// VALUES(1234,1,"2007-06-28 03:00","2007-06-28 06:00") using (var data = new ReduxItems()) { var programmes = (from prog in data.pips_programmes //orderby prog.ServiceId, prog.StartTime select prog).ToList(); programmes = (from prog in programmes orderby prog.service_id, prog.start_gmt select prog).ToList(); PipsProgramme prev = null; using (var newdata = new ReduxItems()) { foreach (var prog in programmes) { if (prev != null && prev.service_id == prog.service_id && prev.end_gmt < prog.start_gmt) { Gap gap = new Gap { pips_id = prog.id, service_id = prog.service_id, gapstart = prev.end_gmt, gapend = prog.start_gmt }; newdata.gaps.Add(gap); Dispatcher.Invoke((MyDelegate)delegate { gapLabel.Content = string.Format("{0}", gap.gapstart); }); } if (prev == null || prog.service_id != prev.service_id || prog.end_gmt > prev.end_gmt) { prev = prog; } } newdata.SaveChanges(); } Dispatcher.Invoke((MyDelegate)delegate { gapGrid.ItemsSource = data.gaps; }); } }) Link To Source File
Par2NET FastCRC32.cs Task.Factory.StartNew(() => { GenerateCRC32Table(); GenerateWindowTable(window); windowMask = ComputeWindowMask(window); _mre.Set(); }) Link To Source File
Par2NET FileChecker.cs Task.Factory.StartNew((arg) => { try { object[] args = (object[])arg; byte[] b = (byte[])args[0]; DiskFile df = (DiskFile)args[1]; string f = (string)args[2]; int bs = (int)args[3]; Dictionary hf = (Dictionary)args[4]; MatchType mt = (MatchType)args[5]; int o = (int)args[6]; CheckBuffer(b, df, f, bs, hf, ref mt, o); } finally { //concurrencySemaphore.Release(); } }, new object[] { buffer, diskFile, filename, blocksize, hashfull, matchType, offset }) Link To Source File
Par2NET FileChecker.cs Task.Factory.StartNew((arg) => { try { object[] args = (object[])arg; byte[] b = (byte[])args[0]; DiskFile df = (DiskFile)args[1]; string f = (string)args[2]; int bs = (int)args[3]; Dictionary hf = (Dictionary)args[4]; MatchType mt = (MatchType)args[5]; int o = (int)args[6]; CheckBuffer(b, df, f, bs, hf, ref mt, o); } finally { //concurrencySemaphore.Release(); } }, new object[] { (byte[])buffer.Clone(), diskFile, filename, blocksize, hashfull, matchType, offset }) Link To Source File
Par2NET FileChecker.cs Task.Factory.StartNew((arg) => { try { CheckBufferState innerState = (CheckBufferState)arg; MatchType matchType = MatchType.FullMatch; CheckBuffer(state.Buffer, state.DiskFile, state.FileName, state.BlockSize, state.HashFull, ref matchType, state.Offset); state.MatchType = matchType; // Signal the main thread that the verification is finished. tempState.ManualEvent.Set(); } finally { //concurrencySemaphore.Release(); } }, state) Link To Source File
Par2NET FileVerification.cs Task.Factory.StartNew(() => { if ((ulong)length > filesize - blocknumber * (ulong)length) { length = (ulong)(filesize - blocknumber * (ulong)length); } Debug.Assert(contextfull != null); lock (contextfullLock) { if (blocknumber < blockcount - 1) { contextfull.TransformBlock(buffer, 0, (int)length, null, 0); } else { contextfull.TransformFinalBlock(buffer, 0, (int)length); contextfullAvailable.Set(); } } }) Link To Source File
Par2NET MainPacket.cs // setid calculation and fileids insertion will occur in Par2RecoverySet.OpenSourceFiles method System.Threading.Tasks.Task.Factory.StartNew((b) => { //FastCRC32.FastCRC32 crc32 = new FastCRC32.FastCRC32((ulong)b); FastCRC32.FastCRC32 crc32 = FastCRC32.FastCRC32.GetCRC32Instance((ulong)b); }, tmpPacket.blocksize) Link To Source File
Par2NET MainPacket.cs System.Threading.Tasks.Task.Factory.StartNew((b) => { //FastCRC32.FastCRC32 crc32 = new FastCRC32.FastCRC32((ulong)b); FastCRC32.FastCRC32 crc32 = FastCRC32.FastCRC32.GetCRC32Instance((ulong)b); }, tmpPacket.blocksize) Link To Source File
SignalRTicTacToe TicTacToeServer.cs Task.Factory.StartNew(() => { Thread.Sleep(ResetWaitTimeInSeconds*1000); if (_ticTacToeGame.Status == GameState.XWins || _ticTacToeGame.Status == GameState.OWins) { _clientManager.RotateRolesKeepingAsPlayer(_ticTacToeGame.Status == GameState.XWins ? ClientRole.PlayerX : ClientRole.PlayerO); } ResetGame(); }) Link To Source File
strokes ParallelStrokesAchievementService.cs Task.Factory.StartNew(() => { /* Technically we create a lot of objects all the time. * It's possible that these objects could have a lifespan longer than just a session. * However maintaining state is always a PITA */ var achievement = (StaticAnalysisAchievementBase)Activator.CreateInstance(a.AchievementType); if (achievement.IsAchievementUnlocked(statisAnalysisSession)) { a.CodeOrigin = achievement.AchievementCodeOrigin; a.IsCompleted = true; unlockedAchievements.Add(a); } }) Link To Source File
CommonLib ProgressTaskViewModel.cs Task.Factory.StartNew(() => { this.ActionWork.Invoke(this); }) Link To Source File
Colombo.Clerk ClerkHandleInterceptor.cs Task.Factory.StartNew(() => { IClerkService clerkService = null; try { clerkService = clerkServiceFactory.CreateClerkService(); if (clerkService != null) { clerkService.Write(auditInfo); } else { var alert = new ClerkServiceUnreachableAlert(auditInfo); Logger.Warn(auditInfo.ToString()); foreach (var colomboAlerter in Alerters) { colomboAlerter.Alert(alert); } } } catch (Exception ex) { Logger.Error("An exception occured while writing clerk information", ex); } finally { if ((clerkService != null) && (clerkService is IClientChannel)) { try { ((IClientChannel)clerkService).Close(); } catch (Exception) { ((IClientChannel)clerkService).Abort(); } } } }) Link To Source File
Remora RemoraHostService.cs Task.Factory.StartNew(() => { try { var context = _httpListener.EndGetContext(result); var remoraAsyncResult = new RemoraAsyncProcessor( RemoraAsyncResultCallback, context, null, Bootstraper.Container); remoraAsyncResult.Process(); } catch (Exception) { if (_httpListener.IsListening) throw; } }) Link To Source File
homestretch-webapi-demo BasicAuthenticationHandler.cs Task.Factory.StartNew(() => new HttpResponseMessage(HttpStatusCode.Unauthorized)) Link To Source File
CrossWord Main.cs Task.Factory.StartNew(() => GenerateAndOutput(gen1, _commandStore)) Link To Source File
Lycanthrope UpdateForm.cs Task.Factory.StartNew(() => { up.DoUpdate(ver); WriteLine("自動更新が完了しました!"); WriteLine("Krileを再起動します。しばらくお待ちください..."); System.IO.File.Create(Application.ExecutablePath + ".completed"); System.Threading.Thread.Sleep(100); Application.Exit(); }) Link To Source File
Lycanthrope QueryEditorViewModel.cs Task.Factory.StartNew(() => { try { var filter = QueryConverter.ToFilter(_queryString); _isValidQuery = true; } catch (Exception e) { _errorString = e.Message; _isValidQuery = false; } DispatcherHelper.UIDispatcher.BeginInvoke(() => RaisePropertyChanged(() => IsValidQuery)); }) Link To Source File
Mystique UserStreamsConnection.cs Task.Factory.StartNew(() => StartPump()) Link To Source File
Mystique ImageCacheStorage.cs Task.Factory.StartNew(() => GCCacheStorage(null)) Link To Source File
Mystique AccountScheduler.cs Task.Factory.StartNew(() => { try { // テストを飛ばす ApiHelper.ExecApi(() => info.Test()); } catch { } }) Link To Source File
Mystique SupervisorScheduler.cs Task.Factory.StartNew(task.DoWork) Link To Source File
Mystique Initializer.cs Task.Factory.StartNew(() => Inscribe.Communication.CruiseControl.AutoCruiseSchedulerManager.Begin()) Link To Source File
Mystique Initializer.cs Task.Factory.StartNew(() => ConnectionManager.RefreshReceivers()) Link To Source File
Mystique CachedConcurrentObservableCollection.cs Task.Factory.StartNew(() => Commit(invalidateCollection)) Link To Source File
Mystique FilterList.cs Task.Factory.StartNew(() => { try { ListStorage.GetListMembers(this.listUser, this.listName).ToArray(); this.RaiseRequireReaccept(); } catch { } }) Link To Source File
Mystique FilterMentionTree.cs Task.Factory.StartNew(() => RecursiveCheckId(id)) Link To Source File
Mystique FilterMentionTree.cs Task.Factory.StartNew(() => RecursiveCheckId(status.Id)) Link To Source File
Mystique FilterMentionTree.cs Task.Factory.StartNew(() => TweetStorage.GetAll(tvm => (tvm.Status is TwitterStatus) && ((TwitterStatus)tvm.Status).InReplyToStatusId == id) .ForEach(tvm => tvm.RefreshInReplyToInfo())) Link To Source File
Mystique FilterMentionTree.cs Task.Factory.StartNew(() => receive()) Link To Source File
Mystique NotificationCore.cs Task.Factory.StartNew(() => { if (isPlaying) return; isPlaying = true; try { using (var soundplayer = new SoundPlayer(path)) { soundplayer.PlaySync(); } } catch (Exception ex) { ExceptionStorage.Register(ex, ExceptionCategory.InternalError, "通知音の再生ができませんでした。"); } isPlaying = false; }) Link To Source File
Mystique HashtagStorage.cs Task.Factory.StartNew(() => { RegularExpressions.HashRegex.Matches(e.Tweet.TweetText) .OfType() .Select(m => m.Value) .ForEach(t => AddHashtag(t)); }) Link To Source File
Mystique UrlTooltipViewModel.cs Task.Factory.StartNew(() => { if (Setting.Instance.TweetExperienceProperty.UrlResolveMode == Configuration.Settings.UrlResolve.OnPointed) url = ShortenManager.Extract(url); ResolvedUrl = url; ImageLinkUrl = UploaderManager.TryResolve(url); }) Link To Source File
Mystique FollowManagerViewModel.cs Task.Factory.StartNew(() => { try { Parallel.ForEach(Relations, r => r.CommitRelation()); } finally { DispatcherHelper.BeginInvoke(() => { IsCommunicating = false; callback(); }); } }) Link To Source File
Mystique NotifierViewModel.cs Task.Factory.StartNew(() => Thread.Sleep(Setting.Instance.ExperienceProperty.TwitterActionNotifyShowLength)) Link To Source File
Mystique FilterQueryEditorViewModel.cs Task.Factory.StartNew(() => { try { this.FilterCluster = QueryCompiler.ToFilter(value); this._result = "クエリは正しく解釈できました。"; this.Success = true; } catch (Exception e) { this.FilterCluster = null; this.Success = false; this._result = e.Message; } RaisePropertyChanged(() => Result); }) Link To Source File
Mystique AuthenticateViewModel.cs Task.Factory.StartNew(() => { try { string token = null; var uri = ApiHelper.ExecApi(() => this._credentialCore.GetProviderAuthUrl(out token)); if (uri == null || String.IsNullOrEmpty(token)) { throw new Exception("リターン情報が空です。(uri:" + (uri == null ? "NULL" : uri.OriginalString) + " / token: " + token); } this.requestToken = token; Browser.Start(uri.OriginalString); } catch (Exception e) { DispatcherHelper.BeginInvoke(() => this.Messenger.Raise(new InformationMessage( "認証を開始できませんでした。" + Environment.NewLine + "もう一度試してください。" + Environment.NewLine + "エラー: " + e.Message, "認証開始エラー", System.Windows.MessageBoxImage.Error, "Inform"))); } finally { this.IsStandby = true; } }) Link To Source File
Mystique AuthenticateViewModel.cs Task.Factory.StartNew(() => { try { long userId; string userScreenName; if (this._credentialCore.GetAccessToken( this.requestToken, this.PinString, out userId, out userScreenName) && userId != 0) { this._credentialCore.NumericId = userId; this._credentialCore.ScreenName = userScreenName; this.Success = true; DispatcherHelper.BeginInvoke(() => Messenger.Raise(new WindowActionMessage("Close", WindowAction.Close))); } else { requestToken = String.Empty; PinString = String.Empty; throw new Exception("認証に失敗しました。PINの入力ミスの可能性があります。"); } } catch (WebException wex) { string errormsg = string.Empty; if (wex.Response != null) { using (var sr = new StreamReader(wex.Response.GetResponseStream())) { errormsg = sr.ReadToEnd(); } } else { errormsg = "データはありません。"; } DispatcherHelper.BeginInvoke(() => Messenger.Raise(new InformationMessage( "認証に失敗しました。もう一度やり直してください。" + Environment.NewLine + "エラーデータ:" + errormsg + Environment.NewLine + wex.Message, "認証エラー", System.Windows.MessageBoxImage.Error, "Inform"))); } catch (Exception ex) { DispatcherHelper.BeginInvoke(() => Messenger.Raise(new InformationMessage( "認証に失敗しました。もう一度やり直してください。" + Environment.NewLine + ex.Message, "認証エラー", System.Windows.MessageBoxImage.Error, "Inform"))); } finally { this.IsStandby = true; } }) Link To Source File
Mystique AboutViewModel.cs Task.Factory.StartNew(() => CheckUpdate()) Link To Source File
Mystique SettingViewModel.cs Task.Factory.StartNew(() => ConnectionManager.RefreshReceivers()) Link To Source File
Mystique TabEditorViewModel.cs Task.Factory.StartNew(() => ConnectionManager.RemoveQuery(parameter)) Link To Source File
Mystique TabEditorViewModel.cs Task.Factory.StartNew(() => { try { var lists = acc.GetFollowingListsAll(_selectedScreenName); if (lists != null) lists.ForEach(l => acc.RegisterFollowingList(l)); RaisePropertyChanged(() => ListItems); } catch { this.Messenger.Raise(new InformationMessage("リスト情報を取得できません。", "リストロードエラー", System.Windows.MessageBoxImage.Error, "WarningMessage")); } finally { IsListLoading = false; } }) Link To Source File
Mystique InputBlockViewModel.cs Task.Factory.StartNew(() => ConnectionManager.RefreshReceivers()) Link To Source File
Mystique InputBlockViewModel.cs Task.Factory.StartNew(() => { using (var n = NotifyStorage.NotifyManually("アカウント情報を取得、更新しています...")) { AccountStorage.Accounts.ForEach(i => Communication.UserInformationManager.ReceiveInidividualInfo(i)); } }) Link To Source File
Mystique InputBlockViewModel.cs Task.Factory.StartNew(() => { TweetStorage.GetAll(tvm => (DateTime.Now - tvm.CreatedAt).TotalHours > 12) .ForEach(t => TweetStorage.Remove(t.bindingId)); }) Link To Source File
Mystique InputBlockViewModel.cs Task.Factory.StartNew(() => { var profimgs = currentTarget.Select(ai => ai.ProfileImage).ToArray(); DispatcherHelper.BeginInvoke(() => ImageStackingViewViewModel.ImageUrls = profimgs); }) Link To Source File
Mystique TimelineListCoreViewModel.cs Task.Factory.StartNew(() => this._tweetsSource.ToArrayVolatile() .ForEach(vm => vm.PendingColorChanged())) Link To Source File
Mystique TimelineListCoreViewModel.cs Task.Factory.StartNew(() => this.InvalidateCache()) Link To Source File
Mystique TimelineListCoreViewModel.cs // Generate timeline Task.Factory.StartNew(() => this.InvalidateCache()) Link To Source File
Mystique TimelineListCoreViewModel.cs Task.Factory.StartNew(() => InvalidateCache()) Link To Source File
Mystique TimelineListCoreViewModel.cs Task.Factory.StartNew(() => this.InvalidateCache()) Link To Source File
Mystique UserPageViewModel.cs Task.Factory.StartNew(() => { try { var acc = AccountStorage.GetRandom(a => a.Followings.Contains(this.User.TwitterUser.NumericId), true); var tweets = InjectionPoint.UnfoldTimeline(i => acc.GetUserTimeline(userId: this.User.TwitterUser.NumericId, count: 100, includeRts: true, page: i), 100, 5); if (tweets != null) tweets.ForEach(t => TweetStorage.Register(t)); } catch (Exception e) { ExceptionStorage.Register(e, ExceptionCategory.TwitterError, "ユーザータイムラインを受信できませんでした: @" + this.User.TwitterUser.ScreenName, ReceiveTimeline); } finally { IsStandby = true; } }) Link To Source File
Mystique UserPageViewModel.cs Task.Factory.StartNew(() => this.TimelineListCoreViewModel.InvalidateCache()) Link To Source File
Mystique UserPageViewModel.cs Task.Factory.StartNew(() => { try { var user = UserStorage.Lookup(screenName); if (user == null) { var cred = AccountStorage.GetRandom(); if (cred != null) { var ud = ApiHelper.ExecApi(() => cred.GetUserByScreenName(screenName)); if (ud == null) { DispatcherHelper.BeginInvoke(() => this.Messenger.Raise(new Livet.Messaging.InformationMessage( "ユーザー @" + screenName + " の情報を取得できません。" + Environment.NewLine + "ユーザーが存在しない可能性があります。", "ユーザー情報取得エラー", System.Windows.MessageBoxImage.Warning, "InformationMessage"))); this.User = null; return; } else { user = UserStorage.Get(ud); } } } if (user == null) throw new Exception("ユーザー情報がありません。"); User = user; } catch (Exception e) { ExceptionStorage.Register(e, ExceptionCategory.TwitterError, "ユーザー @" + screenName + " の情報を取得できませんでした。"); DispatcherHelper.BeginInvoke(() => this.Messenger.Raise(new Livet.Messaging.InformationMessage( "ユーザー @" + screenName + "の情報を取得できません。", "ユーザー情報取得エラー", System.Windows.MessageBoxImage.Warning, "InformationMessage"))); this.User = null; } finally { IsStandby = true; } }) Link To Source File
Mystique SystemInfoViewModel.cs Task.Factory.StartNew(() => UpdatePostChunk()) Link To Source File
Mystique SystemInfoViewModel.cs Task.Factory.StartNew(() => UpdatePostChunk()) Link To Source File
Mystique SystemInfoViewModel.cs Task.Factory.StartNew(() => { try { desc.RetryAction(); } catch (Exception e) { ExceptionStorage.Register(e, ExceptionCategory.InternalError, "再試行中に問題が発生しました。"); } }) Link To Source File
Mystique TabDependentTweetViewModel.cs Task.Factory.StartNew(() => ApiHelper.ExecApi(() => i.ReportSpam(this.Tweet.Status.User.NumericId))) Link To Source File
Mystique TabDependentTweetViewModel.cs Task.Factory.StartNew(() => this.Parent.BaseTimeline.CoreViewModel.InvalidateCache()) Link To Source File
Mystique TabViewModel.cs Task.Factory.StartNew(() => { Thread.Sleep(Setting.Instance.TimelineExperienceProperty.QueryApplyWait); if (this._queryTextBuffer == value) { this.AnalyzeCurrentQuery(); } }) Link To Source File
Mystique TabViewModel.cs Task.Factory.StartNew(() => cf.TimelineListCoreViewModel.InvalidateCache()) Link To Source File
Mystique TabViewModel.cs Task.Factory.StartNew(() => { IEnumerable tweets; using (NotifyStorage.NotifyManually("タイムラインの内容を取得しています...")) { tweets = this.CurrentForegroundTimeline.CoreViewModel.TweetsSource.ToArrayVolatile(); } var msg = new ConfirmationMessage( "このタブに含まれるすべてのツイートをFavoriteします。" + Environment.NewLine + "(対象ツイート: " + tweets.Count() + "件)" + Environment.NewLine + "よろしいですか?", "全てFavorite", System.Windows.MessageBoxImage.Warning, System.Windows.MessageBoxButton.OKCancel, "Confirm"); this.Parent.Messenger.Raise(msg); if (msg.Response.GetValueOrDefault()) tweets.ForEach(t => t.Favorite()); }) Link To Source File
Mystique TabViewModel.cs Task.Factory.StartNew(() => { IEnumerable tweets; using (NotifyStorage.NotifyManually("タイムラインの内容を取得しています...")) { tweets = this.CurrentForegroundTimeline.CoreViewModel.TweetsSource.ToArrayVolatile(); } var msg = new ConfirmationMessage( "このタブに含まれるすべてのツイートをUnfavoriteします。" + Environment.NewLine + "(対象ツイート: " + tweets.Count() + "件)" + Environment.NewLine + "よろしいですか?", "全てUnfavorite", System.Windows.MessageBoxImage.Warning, System.Windows.MessageBoxButton.OKCancel, "Confirm"); this.Parent.Messenger.Raise(msg); if (msg.Response.GetValueOrDefault()) tweets.ForEach(t => t.Unfavorite()); }) Link To Source File
Mystique TabViewModel.cs Task.Factory.StartNew(() => { IEnumerable tweets; using (NotifyStorage.NotifyManually("タイムラインの内容を取得しています...")) { tweets = this.CurrentForegroundTimeline.CoreViewModel.TweetsSource.ToArrayVolatile(); } var msg = new ConfirmationMessage( "このタブに含まれるすべてのツイートをRetweetします。" + Environment.NewLine + "(対象ツイート: " + tweets.Count() + "件)" + Environment.NewLine + "よろしいですか?", "全てFavorite", System.Windows.MessageBoxImage.Warning, System.Windows.MessageBoxButton.OKCancel, "Confirm"); this.Parent.Messenger.Raise(msg); if (msg.Response.GetValueOrDefault()) { var lai = this.TabProperty.LinkAccountInfos.ToArray(); tweets.OrderBy(t => t.Tweet.CreatedAt) .ForEach(t => PostOffice.Retweet(lai, t.Tweet)); } }) Link To Source File
Mystique TweetViewModel.cs Task.Factory.StartNew(() => ResolvePhotos()) Link To Source File
Mystique TweetStorage.cs Task.Factory.StartNew(() => RaiseStatusAdded(viewModel)) Link To Source File
Mystique TweetStorage.cs Task.Factory.StartNew(() => RaiseStatusRemoved(remobj)) Link To Source File
Mystique TweetStorage.cs Task.Factory.StartNew(() => RaiseStatusRemoved(remobj)) Link To Source File
Mystique TweetStorage.cs Task.Factory.StartNew(() => RaiseStatusStateChanged(tweet)) Link To Source File
Mystique EntryPoint.cs Task.Factory.StartNew(() => { switch (e.EventDescription.Kind) { case EventKind.Follow: CheckFollower(e.EventDescription.SourceUser, e.EventDescription.TargetUser.TwitterUser.ScreenName); break; } }) Link To Source File
Mystique R4SDialogViewModel.cs Task.Factory.StartNew(() => { AccountStorage.Accounts.ForEach(i => ReportForSpam(i, User.TwitterUser)); NotifyStorage.Notify("@" + User.TwitterUser.ScreenName + " をスパム報告しました。"); }) Link To Source File
Mystique Notification.xaml.cs Task.Factory.StartNew(() => { Thread.Sleep(Setting.Instance.NotificationProperty.NotifyWindowShowLength); this.Dispatcher.BeginInvoke(() => this.Close()); }) Link To Source File
Mystique Update.cs Task.Factory.StartNew(() => { try { core.BeginUpdate(); WriteLine("Wait for starting NEW Krile..."); System.IO.File.Create(Application.ExecutablePath + ".completed"); System.Threading.Thread.Sleep(100); Application.Exit(); } catch (SecurityException sex) { MessageBox.Show("シグネチャが一致しません。" + Environment.NewLine + "不正なバイナリをダウンロードしたか、もしくは更新手段に変更があります。" + Environment.NewLine + "お手数ですが、手動での更新をお願いします。" + Environment.NewLine + "message:" + sex.Message, "更新エラー", MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); } catch (Exception ex) { WriteLine("ERROR THROWN:-------------------------------------------------"); WriteLine(ex.ToString()); MessageBox.Show("エラーが発生しました。" + Environment.NewLine + ex.Message, "更新エラー", MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); } }) Link To Source File
Mystique MainForm.cs Task.Factory.StartNew(() => { try { if (!PostString(new Uri("http://krile.starwing.net/report.php"), sb.ToString(), out err)) { if (String.IsNullOrEmpty(err)) err = "何か不思議な力で失敗しました。もう一度試してみてください。"; throw new Exception(err); } this.Invoke(new Action(() => { sendState.Text = "送信完了しました。"; sendProgress.Style = ProgressBarStyle.Continuous; this.Refresh(); })); } catch (Exception ex) { this.Invoke(new Action(() => { MessageBox.Show("アップロードエラー:" + ex.Message); sendState.Text = "送信に失敗しました。"; sendProgress.Style = ProgressBarStyle.Continuous; })); } }) Link To Source File
OCTGN CardDlg.xaml.cs // Async load the cards (to make the GUI snappier with huge DB) Task.Factory.StartNew(() => { _allCards = Database.GetCards(where).ToList(); Dispatcher.BeginInvoke(new Action(() => allList.ItemsSource = _allCards)); }) Link To Source File
PaulTest PerformanceBenchmarkEngine.cs Task.Factory.StartNew(test.Run) Link To Source File
lokad-cloud MemoryProvisioning.cs Task.Factory.StartNew(() => { }) Link To Source File
lokad-cloud-storage QueueStorageProvider.cs Task.Factory.StartNew(() => PutRawMessage(queueMessage, queue, timeToLive, delay)) Link To Source File
lokad-cloud-storage MemoryTableStorageTests.cs Task.Factory.StartNew(() => { for (int k1 = 0; k1 < 10; k1++) { TableStorage.CreateTable("table" + k1.ToString()); } }) Link To Source File
lokad-cqrs Listener.cs Task.Factory.StartNew(() => { try { _listener = new HttpListener(); _listener.Prefixes.Add(prefix); _listener.Start(); } catch (HttpListenerException ex) { if (ex.ErrorCode == 5) { var solution = string.Format( "Make sure to run as admin or reserve prefix. For reservation you can try executing as admin: netsh http add urlacl url={0} user={1}//{2}", prefix, Environment.MachineName, Environment.UserName); SystemObserver.Notify(new ConfigurationWarningEncountered("HttpListener can't connect to " + prefix + ". " + solution, ex)); } else { SystemObserver.Notify(new FailedToStartHttpListener(ex, prefix)); } } catch (Exception ex) { SystemObserver.Notify(new FailedToStartHttpListener(ex, prefix)); } _listener.BeginGetContext(ar => GetContext(ar, token), null); WaitTillAllProcessorsQuit(token); _listener.Stop(); }, token) Link To Source File
lokad-cqrs CqrsEngineHost.cs Task.Factory.StartNew(() => { var watch = Stopwatch.StartNew(); try { Task.WaitAll(tasks, token); } catch(OperationCanceledException) {} SystemObserver.Notify(new EngineStopped(watch.Elapsed)); }) Link To Source File
lokad-cqrs DomainLogView.cs Task.Factory.StartNew(() => { }) Link To Source File
lokad-cqrs HeatMapGenerateTask.cs Task.Factory.StartNew(() => RenderTask( token)) Link To Source File
lokad-cqrs-samples Domain.cs Task.Factory.StartNew(() => { while (!token.IsCancellationRequested) { try { var wait = ExecuteTask(); if (wait == TimeSpan.MaxValue) { // quit task return; } token.WaitHandle.WaitOne(wait); } catch (Exception ex) { Trace.WriteLine(ex.ToString()); token.WaitHandle.WaitOne(TimeSpan.FromMinutes(5)); } } }) Link To Source File
lokad-cqrs-samples Domain.cs Task.Factory.StartNew(() => { while (!token.IsCancellationRequested) { try { var wait = ExecuteTask(); if (wait == TimeSpan.MaxValue) { // quit task return; } token.WaitHandle.WaitOne(wait); } catch (Exception ex) { Trace.WriteLine(ex.ToString()); token.WaitHandle.WaitOne(TimeSpan.FromMinutes(5)); } } }) Link To Source File
lokad-cqrs-samples ScanTaskBlob.cs Task.Factory.StartNew(() => { while (!token.IsCancellationRequested) { try { var timeSpan = Happen(); token.WaitHandle.WaitOne(timeSpan); } catch (Exception ex) { Trace.WriteLine(ex); token.WaitHandle.WaitOne(TimeSpan.FromMinutes(2)); } } }) Link To Source File
FistCore.Lib MembaseHelper.cs Task.Factory.StartNew(() => { while (!result.Result && tries < RetriesCount) { if (!item.Refresh()) throw new NullReferenceException("Item removed from the database or unable to refresh the data."); foreach (string propName in props.Keys) { ReflectionUtil.TrySetPropertyValue(item, propName, props[propName]); } result = item.Client.Cas(StoreMode.Set, item.Key, item.ToJson(), item.CAS); tries++; } if (tries >= RetriesCount) throw new OperationCanceledException("Max retries reached. Update failed for key " + item.Key); }) Link To Source File
FistCore.Lib MembaseHelper.cs Task.Factory.StartNew(() => { while (!result.Result && tries < RetriesCount) { if (!item.Refresh()) throw new NullReferenceException("Item removed from the database or unable to refresh the data."); propValue = (int)ReflectionUtil.GetPublicPropertyValue(item, IntPropName); propValue++; result = item.Client.Cas(StoreMode.Set, item.Key, item.ToJson(), item.CAS); tries++; } if (tries >= RetriesCount) throw new OperationCanceledException("Max retries reached. Update failed for key " + item.Key); }) Link To Source File
FistCore.Lib MembaseHelper.cs Task.Factory.StartNew(() => { while (!result.Result && tries < RetriesCount) { if (!item.Refresh()) throw new NullReferenceException("Item removed from the database or unable to refresh the data."); propValue = (int)ReflectionUtil.GetPublicPropertyValue(item, IntPropName); propValue--; result = item.Client.Cas(StoreMode.Set, item.Key, item.ToJson(), item.CAS); tries++; } if (tries >= RetriesCount) throw new OperationCanceledException("Max retries reached. Update failed for key " + item.Key); }) Link To Source File
OCometNet MessageBroker.cs Task.Factory.StartNew(() => { request.Process(); }) Link To Source File
OCometNet MessageBroker.cs Task.Factory.StartNew(() => { response.ProcessGeneric(() => { return String.Empty; }); }) Link To Source File
machine.specifications TaskSpecificationExtensionsSpecs.cs Task.Factory.StartNew(() => { Thread.Sleep(WaitTimeout); throw new InvalidOperationException("something went wrong"); }) Link To Source File
machine.specifications TaskSpecificationExtensionsSpecs.cs Task.Factory.StartNew(() => Task.WaitAll(Fail(), Fail())) Link To Source File
CaveTalk LoginBoxViewModel.cs Task.Factory.StartNew(() => { Thread.Sleep(2000); this.errorMessage = String.Empty; base.OnPropertyChanged("ErrorMessage"); }) Link To Source File
SIinformer AutoUpdater.cs // запускаем проверку в отдельном потоке Task.Factory.StartNew(() => { done(_CheckUpdates());// возвращаем результат проверки }) Link To Source File
SIinformer DatabaseManager_db4o.cs // запускаем сохранение в отдельном потоке Task.Factory.StartNew(() => { foreach (Author author in InfoUpdater.Authors) { if (author.Changed || SaveAll) { author.Changed = false; SaveAuthor(author); } } SaveCategories(InfoUpdater.Categories); } ) Link To Source File
SIinformer DatabaseManager_db4o.cs Task.Factory.StartNew(() => SaveAuthor(author)) Link To Source File
SIinformer DatabaseManager_db4o.cs Task.Factory.StartNew( () => { using (var documentStore = server.OpenClient()) { var authors = documentStore.Query( x => x != null && !x.author.IsDeleted); foreach (var author in authors) { author.author.Changed = false; list.Add(author.author); } } }) Link To Source File
SIinformer InfoUpdater.cs // запускаем сохранение в отдельном потоке Task.Factory.StartNew(() => { if (SaveAll) { foreach (Author author in Authors) author.Changed = false; Authors.Save(AuthorsFileName); Categories.Save(CategoriesFileName); } else // запишем только, если есть авторы с изменившимися данными { if (Authors.Any(a => a.Changed)) { foreach (Author author in Authors) author.Changed = false; Authors.Save(AuthorsFileName); } Categories.Save(CategoriesFileName); } }) Link To Source File
Catarinum Program.cs Task.Factory.StartNew(() => { while (true) { client.SendRequest(); Thread.Sleep(30000); } }) Link To Source File
MSTest Program.cs Task.Factory.StartNew(DisplayResults) Link To Source File
DynamoIOC ThreadLocalLifetimeTest.cs Task.Factory.StartNew(() => { result3 = container.Resolve(); result4 = container.Resolve(); }) Link To Source File
ChameleonCoder App.xaml.cs Task.Factory.StartNew(() => { Task files = null; if (path != null) { files = Task.Factory.StartNew(() => { try { DefaultFile = DataFile.Open(path); // open the file } catch (FileFormatException) { throw; // Todo: inform user, log } catch (FileNotFoundException) { throw; // Todo: inform user, log } }); } var plugins = Task.Factory.StartNew(() => { Plugins.PluginManager.Load();// load all plugins in the /Component/ folder }); if (files != null) files.Wait(); plugins.Wait(); foreach (var file in DataFile.LoadedFiles) { foreach (XmlElement element in file.GetResources()) AddResource(element, null); // and parse the Xml } }) Link To Source File
ChameleonCoder App.xaml.cs Task.Factory.StartNew(() => { try { DefaultFile = DataFile.Open(path); // open the file } catch (FileFormatException) { throw; // Todo: inform user, log } catch (FileNotFoundException) { throw; // Todo: inform user, log } }) Link To Source File
ChameleonCoder App.xaml.cs Task.Factory.StartNew(() => { Plugins.PluginManager.Load();// load all plugins in the /Component/ folder }) Link To Source File
YUV.KA SaveNodeOutputViewModel.cs Task.Factory.StartNew(() => { using (stream) YuvEncoder.Encode(stream, frames); TryClose(); }) Link To Source File
nuget PackageRestoreManager.cs Task.Factory.StartNew(() => { IVsPackageManager packageManager = _packageManagerFactory.CreatePackageManager(); IPackageRepository localRepository = packageManager.LocalRepository; var projectReferences = GetAllPackageReferences(packageManager); foreach (var reference in projectReferences) { if (!localRepository.Exists(reference.Id, reference.Version)) { packageManager.InstallPackage(reference.Id, reference.Version, ignoreDependencies: true, allowPrereleaseVersions: true); } } }) Link To Source File
nuget ProductUpdateService.cs Task.Factory.StartNew(() => { try { Version installedVersion, newVersion; if (UpdateWorker.CheckForUpdate(out installedVersion, out newVersion)) { RaiseUpdateEvent(new ProductUpdateAvailableEventArgs(installedVersion, newVersion)); } } catch { // Swallow all exceptions. We don't want to take down vs, if the VS extension // gallery happens to be down. } }) Link To Source File
SuperSocket AppServer.cs Task.Factory.StartNew((s) => { ((TAppSession)s).Close(CloseReason.ServerShutdown); }, sessions[i].Value) Link To Source File
SuperSocket MainViewModel.cs Task.Factory.StartNew(() => StartSend(socket)) Link To Source File
SuperSocket AppServer.cs Task.Factory.StartNew((s) => { ((TAppSession)s).Close(CloseReason.ServerShutdown); }, sessions[i].Value) Link To Source File
Schumix2 CalendarAddon.cs Task.Factory.StartNew(() => { string channel = sIRCMessage.Channel.ToLower(); if(sChannelInfo.FSelect(IFunctions.Antiflood) && sChannelInfo.FSelect(IChannelFunctions.Antiflood, channel)) { string nick = sIRCMessage.Nick.ToLower(); int i = 0; foreach(var list in FloodList) { if(nick == list.Name && channel == list.Channel) { list.Message++; i++; } } if(nick == "py-ctcp") return; if(i > 0) return; FloodList.Add(new Flood(nick, channel)); } }) Link To Source File
Schumix2 Calendar.cs Task.Factory.StartNew(() => Flood()) Link To Source File
Schumix2 Calendar.cs Task.Factory.StartNew(() => Unban()) Link To Source File
Schumix2 Calendar.cs Task.Factory.StartNew(() => CalendarTimeRemove()) Link To Source File
Schumix2 ExtraAddon.cs Task.Factory.StartNew(() => { if(sFunctions.AutoKick("privmsg", sIRCMessage.Nick, sIRCMessage.Channel)) return; }) Link To Source File
Schumix2 ExtraAddon.cs Task.Factory.StartNew(() => { if(sChannelInfo.FSelect(IFunctions.Automode) && sChannelInfo.FSelect(IChannelFunctions.Automode, sIRCMessage.Channel)) { AutoMode = true; ModeChannel = sIRCMessage.Channel.ToLower(); sSender.NickServStatus(sIRCMessage.Nick); } }) Link To Source File
Schumix2 ExtraAddon.cs Task.Factory.StartNew(() => { if(sChannelInfo.FSelect(IFunctions.Randomkick) && sChannelInfo.FSelect(IChannelFunctions.Randomkick, sIRCMessage.Channel)) { if(sIRCMessage.Args.IsUpper() && sIRCMessage.Args.Length > 4) sSender.Kick(sIRCMessage.Channel, sIRCMessage.Nick, sLManager.GetWarningText("CapsLockOff", sIRCMessage.Channel)); } }) Link To Source File
Schumix2 ExtraAddon.cs Task.Factory.StartNew(() => sFunctions.HLMessage(sIRCMessage)) Link To Source File
Schumix2 ExtraAddon.cs Task.Factory.StartNew(() => sFunctions.Message(sIRCMessage)) Link To Source File
Schumix2 ExtraAddon.cs Task.Factory.StartNew(() => { if(sChannelInfo.FSelect(IFunctions.Webtitle) && sChannelInfo.FSelect(IChannelFunctions.Webtitle, sIRCMessage.Channel)) { if(!SchumixBase.UrlTitleEnabled) return; if(sIRCMessage.Nick.ToLower() == "py-bopm") return; var urlsin = sUtilities.GetUrls(sIRCMessage.Args); if(urlsin.Count <= 0) return; try { Parallel.ForEach(urlsin, url => sFunctions.HandleWebTitle(sIRCMessage, url)); return; } catch(Exception e) { Log.Error("ExtraAddon", "Invalid webpage address: {0}", e.Message); return; } } }) Link To Source File
Schumix2 Console.cs Task.Factory.StartNew(() => ConsoleRead()) Link To Source File
Schumix2 Config.cs Task.Factory.StartNew(() => { Log.Notice("Schumix", sLConsole.Config("Text9")); Log.Notice("Schumix", sLConsole.Config("Text10"), number); for(int i = 0; i < number; i++) { string file = !xmldoc.SelectSingleNode("Server/Schumixs/Schumix" + i + "/Config/File").IsNull() ? xmldoc.SelectSingleNode("Server/Schumixs/Schumix" + i + "/Config/File").InnerText : _schumix0file; string dir = !xmldoc.SelectSingleNode("Server/Schumixs/Schumix" + i + "/Config/Directory").IsNull() ? xmldoc.SelectSingleNode("Server/Schumixs/Schumix" + i + "/Config/Directory").InnerText : _schumix0directory; string ce = !xmldoc.SelectSingleNode("Server/Schumixs/Schumix" + i + "/Config/ConsoleEncoding").IsNull() ? xmldoc.SelectSingleNode("Server/Schumixs/Schumix" + i + "/Config/ConsoleEncoding").InnerText : _schumix0consoleencoding; string lo = !xmldoc.SelectSingleNode("Server/Schumixs/Schumix" + i + "/Config/Locale").IsNull() ? xmldoc.SelectSingleNode("Server/Schumixs/Schumix" + i + "/Config/Locale").InnerText : _schumix0locale; sSchumix.Start(file, dir, ce, lo, sUtilities.GetRandomString()); Thread.Sleep(10*1000); } }) Link To Source File
Schumix2 Schumix.cs Task.Factory.StartNew(() => Start(_processlist[ll].File, _processlist[ll].Dir, _processlist[ll].Encoding, _processlist[ll].Locale, _processlist[ll].Identify, _processlist[ll].Configs)) Link To Source File
Schumix2 Network.cs Task.Factory.StartNew(() => sChannelInfo.ChannelList()) Link To Source File
Schumix2 Network.cs Task.Factory.StartNew(() => HandleIrcCommand(IrcMessage)) Link To Source File
SwarmIntelligence MainWindow.xaml.cs Task.Factory .StartNew(model.Turn) Link To Source File
SwarmIntelligence MainWindow.xaml.cs Task.Factory .StartNew(model.Initialize) Link To Source File
ServiceBusPatterns4Clients Bus.cs Task.Factory.StartNew(() => SendInternal(message)) Link To Source File
LunchCrawler LunchRestaurantAnalyzer.cs Task.Factory.StartNew(() => { LunchMenu parseResult = null; foreach (var strategy in strategies) { parseResult = strategy.ParseLunchMenu(restaurant); // TODO: confidence settings in DB if (parseResult.Confidence > 0.90M) { break; } } CompleteLunchRestaurantAnalysis(parseResult); }) Link To Source File
NugetCracker PackageRestoreManager.cs Task.Factory.StartNew(() => { IVsPackageManager packageManager = _packageManagerFactory.CreatePackageManager(); IPackageRepository localRepository = packageManager.LocalRepository; var projectReferences = GetAllPackageReferences(packageManager); foreach (var reference in projectReferences) { if (!localRepository.Exists(reference.Id, reference.Version)) { packageManager.InstallPackage(reference.Id, reference.Version, ignoreDependencies: true, allowPrereleaseVersions: true); } } }) Link To Source File
NugetCracker ProductUpdateService.cs Task.Factory.StartNew(() => { try { Version installedVersion, newVersion; if (UpdateWorker.CheckForUpdate(out installedVersion, out newVersion)) { RaiseUpdateEvent(new ProductUpdateAvailableEventArgs(installedVersion, newVersion)); } } catch { // Swallow all exceptions. We don't want to take down vs, if the VS extension // gallery happens to be down. } }) Link To Source File
NewsService ScheduleScraper.cs Task.Factory.StartNew(Scraper.Scraper.DownloadHtml) Link To Source File
GllEditor FormMain.cs Task.Factory.StartNew(() => { var fileExt = Path.GetExtension(fileName); if (_FileExtensionToRule.Any(kvp => string.Compare(kvp.Key, fileExt, true) == 0)) { lock(_SyncObjForm) _Rule = _FileExtensionToRule[fileExt]; } else { lock (_SyncObjForm) _Rule = new RuleGrass(); } var source = File.ReadAllText(fileName, Encoding.UTF8);//とりあえずUTF8オンリーで return source; }) Link To Source File
ncqrs ElementFetcher.cs Task.Factory.StartNew(() => Fetch(directive)) Link To Source File
ncqrs MsSqlServerEventStoreTests.cs Task.Factory.StartNew(() => { var changeEvent = new CustomerNameChanged(DateTime.Now.Ticks.ToString()) { CustomerId = theEventSourceId }; var eventStream = Prepare.Events(changeEvent) .ForSourceUncomitted(theEventSourceId, Guid.NewGuid(), 2); try { targetStore.Store(eventStream); } catch (ConcurrencyException) { concurrencyExceptionThrown = true; } targetStore.ReadFrom(theEventSourceId, long.MinValue, long.MaxValue); }) Link To Source File
ncqrs MsSqlServerEventStoreTests.cs Task.Factory.StartNew(() => { var theEventSourceId = Guid.NewGuid(); var theCommitId = Guid.NewGuid(); var eventStream = Prepare.Events(new CustomerCreatedEvent(Task.CurrentId.ToString(), 35)) .ForSourceUncomitted(theEventSourceId, theCommitId); // should not be receiving a deadlock targetStore.Store(eventStream); }) Link To Source File
MusicCA MainWindow.xaml.cs Task.Factory.StartNew(RenderCA) Link To Source File
NecroNetToolkit MailBot.cs Task.Factory.StartNew(() => SmtpClient.Send(message)) Link To Source File
nSt.Scorpio PollingSensor.cs Task.Factory.StartNew(() => { try { TSensorValue previousVal = default(TSensorValue); TSensorValue sensorVal; for (; ; ) { DateTime preDate = DateTime.Now; var ok = GetValue(out sensorVal); if (ok && ValueChanged(previousVal, sensorVal)) { RaiseEventOnMainThread(OnChange, this, new SensorEventArgs(sensorVal)); previousVal = sensorVal; } // sleep for the necessary amount of time DateTime postDate = DateTime.Now; TimeSpan intervalRemainder = TimeResolution - (postDate - preDate); Thread.Sleep((int)Math.Max(intervalRemainder.TotalMilliseconds, DefaultTimeResolution.TotalMilliseconds)); cancellation.Token.ThrowIfCancellationRequested(); } } catch (OperationCanceledException) { Debug.WriteLine(Name + " poller interrupted."); } catch (Exception ex) { Debug.WriteLine(string.Format("{0}/n{1}", ex.Message, ex.Source)); } }, cancellation.Token) Link To Source File
nSt.Scorpio Motor.cs // parellelize this slow command Task.Factory.StartNew(() => { Brick.SetMotorState(MotorPort, state); Debug.WriteLine("Motor on Port " + MotorPort.ToString() + ": " + state.Power + "%"); }) Link To Source File
nSt.Scorpio TwoMotorWalkBehavior.cs Task.Factory.StartNew(() => { Start(leftPower, rightPower); Thread.Sleep(forHowLong); Interrupt(); WalkTask = null; }) Link To Source File
ClinImIm SelectImagesViewModel.cs Task.Factory.StartNew(() => LoadFiles(drivePath)) Link To Source File
ClinImIm SelectDriveViewModel.cs Task.Factory.StartNew(() => LoadFiles(Model.SelectedDrivePath)) Link To Source File
WCFWeb MediaTypeFormatter.cs Task.Factory.StartNew(() => this.OnWriteToStream(type, value, stream, contentHeaders, context)) Link To Source File
WCFWeb ObjectContentTests.cs Task.Factory.StartNew(() => { taskRan = true; }) Link To Source File
WCFWeb ObjectContentTests.cs Task.Factory.StartNew(() => { }) Link To Source File
Disruptor-net DiamondPath1P3CDisruptorWithAffinityPerfTest.cs Task.Factory.StartNew( () => { for (long i = 0; i < Iterations; i++) { var sequence = _ringBuffer.Next(); _ringBuffer[sequence].Value = i; _ringBuffer.Publish(sequence); } }, CancellationToken.None, TaskCreationOptions.None, _scheduler) Link To Source File
Disruptor-net MultiCast1P3CDisruptorWithAffinityPerfTest.cs Task.Factory.StartNew( () => { for (long i = 0; i < Iterations; i++) { var sequence = _ringBuffer.Next(); _ringBuffer[sequence].Value = i; _ringBuffer.Publish(sequence); } }, CancellationToken.None, TaskCreationOptions.None, _scheduler) Link To Source File
Disruptor-net Pipeline3StepLatencyDisruptorWithAffinityPerfTest.cs Task.Factory.StartNew( () => { for (long i = 0; i < Iterations; i++) { var sequence = _ringBuffer.Next(); _ringBuffer[sequence].Value = Stopwatch.GetTimestamp(); _ringBuffer.Publish(sequence); var pauseStart = Stopwatch.GetTimestamp(); while (PauseNanos > (Stopwatch.GetTimestamp() - pauseStart) * TicksToNanos) { // busy spin } } }, CancellationToken.None, TaskCreationOptions.None, _scheduler) Link To Source File
Disruptor-net Pipeline3StepDisruptorWithAffinityPerfTest.cs Task.Factory.StartNew( ()=> { var operandTwo = OperandTwoInitialValue; for (long i = 0; i < Iterations; i++) { var sequence = _ringBuffer.Next(); var evt = _ringBuffer[sequence]; evt.OperandOne = i; evt.OperandTwo = operandTwo--; _ringBuffer.Publish(sequence); } }, CancellationToken.None, TaskCreationOptions.None, _scheduler) Link To Source File
Disruptor-net Sequencer3P1CDisruptorWithAffinityPerfTest.cs Task.Factory.StartNew(_valueProducers[i].Run, CancellationToken.None, TaskCreationOptions.None, _scheduler) Link To Source File
Disruptor-net Sequencer3P1CDisruptorWithAffinityPerfTest.cs Task.Factory.StartNew(_valueProducers[NumProducers - 1].Run, CancellationToken.None, TaskCreationOptions.None, _scheduler) Link To Source File
Disruptor-net UniCast1P1CBatchDisruptorWithAffinityPerfTest.cs Task.Factory.StartNew( () => { long offset = 0; for (long i = 0; i < Iterations; i += batchSize) { _ringBuffer.Next(batchDescriptor); for (long sequence = batchDescriptor.Start; sequence <= batchDescriptor.End; sequence++) { _ringBuffer[sequence].Value = offset++; } _ringBuffer.Publish(batchDescriptor); } }, CancellationToken.None, TaskCreationOptions.None, _scheduler) Link To Source File
Disruptor-net UniCast1P1CDisruptorWithAffinityPerfTest.cs Task.Factory.StartNew( () => { for (long i = 0; i < Iterations; i++) { long sequence = _ringBuffer.Next(); _ringBuffer[sequence].Value = i; _ringBuffer.Publish(sequence); } }, CancellationToken.None, TaskCreationOptions.None, _scheduler) Link To Source File
MXML2MuseScore MainWindowViewModel.cs Task.Factory.StartNew(() => { var museScore = new MuseScoreApp(); museScore.ConvertXMLtoMuseScore(CurrentDocument.FileName); }) Link To Source File
MXML2MuseScore MainWindowViewModel.cs Task.Factory.StartNew(() => _currentDocument.Save()) Link To Source File
Genesis InternalImporter.cs Task.Factory.StartNew(() => { using (ExcelFile file = parser.GetExcelFile()) { ExcelWorksheet excelWorksheet = parser.GetExcelWorksheet(file); RowReader rowReader = parser.GetRowReader(); worksheetReader = new WorksheetReader(excelWorksheet, rowReader); try { Task.Factory .StartNew(Import, cancellationToken) .ContinueWith(x => { if (CompletedAction != null) CompletedAction.Invoke(); }, CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, synchronizedScheduler) .Wait(); } catch (AggregateException ae) { var exceptions = ae.Flatten(); if (exceptions.InnerExceptions.First(x => x is TaskCanceledException) != null) { Task.Factory.StartNew(() => { if (CancelledAction != null) CancelledAction.Invoke(); }, CancellationToken.None, TaskCreationOptions.None, synchronizedScheduler); } exceptions.Handle(e => e is TaskCanceledException); } } }, cancellationToken) Link To Source File
Genesis LocalityViewModel.cs Task.Factory.StartNew(() => { using (GenesisContext c = new GenesisContext()) { var locality = c.Localities.Single(l => l.Id == this.locality.Id); var alleles = (from mouse in locality.Mice from allAlleles in mouse.Alleles where allAlleles.Allele.Gene.Name == "Btk" group allAlleles by allAlleles.Allele.Value).ToArray(); double d = alleles.Where(a => a.Key == "d").Select(r => r.Count()).SingleOrDefault(); double m = alleles.Where(a => a.Key == "m").Select(r => r.Count()).SingleOrDefault(); if (d + m == 0) { return -1; } return m / (d + m); } }) Link To Source File
Experiments CompressedFileSearcher.cs Task.Factory.StartNew(() => m_spanMatches.AsParallel().ForAll(s => SearchSpan(s, toFind))) Link To Source File
CodingDojoHelper InterceptKeys.cs Task.Factory.StartNew(() => { var stopwatch = new Stopwatch(); stopwatch.Start(); while (stopwatch.Elapsed.CompareTo(maxWait) < 0 && _lastKey == Keys.None) System.Threading.Thread.Sleep(100); callback.Invoke(_lastKey); }) Link To Source File
CodingDojoHelper PlaylistSoundPlayer.cs Task.Factory.StartNew(PlayAll) Link To Source File
Automapper MultiThreadingIssues.cs Task.Factory.StartNew( doMapping ) Link To Source File
Dominion Simulation.cs Task.Factory.StartNew(() => RunGame(temp, startingConfig)) Link To Source File
SSharp FixedBugs.cs Task.Factory.StartNew( () => { System.Threading.Thread.Sleep(500); try { if (GetCustomersCompleted != null) { GetCustomersCompleted.Invoke(this, EventArgs.Empty); } } catch(Exception e) { v = e.ToString(); } finally { busy = false; } }) Link To Source File
coapp InstallationPanel.xaml.cs Task.Factory.StartNew(() => { Invoke(() => { Thinking.Visibility = Visibility.Visible; }); for (var i = 0; i <= 100; i += 1) { var p = i; Thread.Sleep(20); Invoke(() => { progressBar1.Value = p; }); } Invoke(() => { Downloading.Visibility = Visibility.Visible; }); for (var i = 0; i <= 100; i += 1) { var p = i; Thread.Sleep(40); Invoke(() => { progressBar1.Value = p; }); } Invoke(() => { Installing.Visibility = Visibility.Visible; }); for (var i = 0; i <= 100; i += 1) { var p = i; Thread.Sleep(60); Invoke(() => { progressBar1.Value = p; }); } Invoke(() => { InstallationMessages.Visibility = Visibility.Collapsed; }); Invoke(() => { CompletedMessage.Visibility = Visibility.Visible; CancelText.Text = "Finish"; }); }) Link To Source File
coapp AsyncConsoleProgram.cs CoTask.Factory.StartNew(() => { Main(args); }, CancellationTokenSource.Token, new DebugMessage { WriteLine = (text) => { Console.WriteLine("[DEBUG][{0}] {1}", ++_counter,text); } }) Link To Source File
coapp CoTaskFactory.cs StartNew(action, Tasklet.CurrentCancellationToken, CreationOptions, Scheduler, new [] { messageHandlers }) Link To Source File
coapp CoTaskFactory.cs StartNew(action, Tasklet.CurrentCancellationToken, creationOptions, Scheduler, new[] { messageHandlers }) Link To Source File
coapp CoTaskFactory.cs StartNew(action, cancellationToken, CreationOptions, Scheduler, new[] { messageHandlers }) Link To Source File
coapp CoTaskFactory.cs StartNew(action, cancellationToken, creationOptions, scheduler, new[] { messageHandlers }) Link To Source File
coapp CoTaskFactory.cs StartNew(action, state, Tasklet.CurrentCancellationToken, CreationOptions, Scheduler, new[] { messageHandlers }) Link To Source File
coapp CoTaskFactory.cs StartNew(action, state, Tasklet.CurrentCancellationToken, creationOptions, Scheduler, new[] { messageHandlers }) Link To Source File
coapp CoTaskFactory.cs StartNew(action, state, cancellationToken, CreationOptions, Scheduler, new[] { messageHandlers }) Link To Source File
coapp CoTaskFactory.cs StartNew(action, state, cancellationToken, creationOptions, scheduler, new[] { messageHandlers }) Link To Source File
coapp CoTaskFactory.cs StartNew(function, Tasklet.CurrentCancellationToken, CreationOptions, Scheduler, new[] { messageHandlers }) Link To Source File
coapp CoTaskFactory.cs StartNew(function, Tasklet.CurrentCancellationToken, creationOptions, Scheduler, new[] { messageHandlers }) Link To Source File
coapp CoTaskFactory.cs StartNew(function, cancellationToken, CreationOptions, Scheduler, new[] { messageHandlers }) Link To Source File
coapp CoTaskFactory.cs StartNew(function, cancellationToken, creationOptions, scheduler, new[] { messageHandlers }) Link To Source File
coapp CoTaskFactory.cs StartNew(function, state, Tasklet.CurrentCancellationToken, CreationOptions, Scheduler, new[] { messageHandlers }) Link To Source File
coapp CoTaskFactory.cs StartNew(function, state, Tasklet.CurrentCancellationToken, creationOptions, Scheduler, new[] { messageHandlers }) Link To Source File
coapp CoTaskFactory.cs StartNew(function, state, cancellationToken, CreationOptions, Scheduler, new[] { messageHandlers }) Link To Source File
coapp CoTaskFactory.cs StartNew(function, state, cancellationToken, creationOptions, scheduler, new[] { messageHandlers }) Link To Source File
coapp Scribe.cs Task.Factory.StartNew(() => { try { if( !file.Contains(@"/")) { file = Path.Combine(currentDirectory, file); } if (!file.ToLowerInvariant().Contains("coapptraceipc")) { var f = _trace.Processes[pid].Files[file]; f.Handle = handle; f.created = created; } } catch (Exception e) { Debug.Print("[Trace]" + e.Message); Debug.Print(e.StackTrace.Replace(" at", "[Trace] at")); } }) Link To Source File
coapp Scribe.cs Task.Factory.StartNew(() => { try { if (!file.Contains(@"/")) { file = Path.Combine(currentDirectory, file); } _trace.Processes[pid].Files[file].deleted = true; } catch (Exception e) { Debug.Print("[Trace]" + e.Message); Debug.Print(e.StackTrace.Replace(" at", "[Trace] at")); } }) Link To Source File
coapp Scribe.cs Task.Factory.StartNew(() => { try { _trace.Processes[pid].Files[before].moved = true; _trace.Processes[pid].Files[before].movedTo = after; } catch (Exception e) { Debug.Print("[Trace]" + e.Message); Debug.Print(e.StackTrace.Replace(" at", "[Trace] at")); } }) Link To Source File
coapp Scribe.cs Task.Factory.StartNew(() => { try { var f = _trace.Processes[pid].FilesByHandle[handle]; if (f != null) f.read = true; } catch (Exception e) { Debug.Print("[Trace]" + e.Message); Debug.Print(e.StackTrace.Replace(" at", "[Trace] at")); } }) Link To Source File
coapp Scribe.cs Task.Factory.StartNew(() => { try { var f = _trace.Processes[pid].FilesByHandle[handle]; if (f != null) f.write = true; } catch (Exception e) { Debug.Print("[Trace]" + e.Message); Debug.Print(e.StackTrace.Replace(" at", "[Trace] at")); } }) Link To Source File
coapp Scribe.cs Task.Factory.StartNew(() => { try { _trace.Processes[pid].Files[source].copied = true; _trace.Processes[pid].Files[source].copiedTo = target; } catch (Exception e) { Debug.Print("[Trace]" + e.Message); Debug.Print(e.StackTrace.Replace(" at", "[Trace] at")); } }) Link To Source File
coapp Scribe.cs Task.Factory.StartNew(() => { try { if (!file.Contains(@"/")) { file = Path.Combine(currentDirectory, file); } _trace.Processes[pid].Files[file].probed = true; } catch (Exception e) { Debug.Print("[Trace]" + e.Message); Debug.Print(e.StackTrace.Replace(" at", "[Trace] at")); } }) Link To Source File
coapp Scribe.cs Task.Factory.StartNew(() => { try { var e = _trace.Processes[pid].Environment[varName]; if (e != null) e.referenced = true; } catch (Exception e) { Debug.Print("[Trace]" + e.Message); Debug.Print(e.StackTrace.Replace(" at", "[Trace] at")); } }) Link To Source File
coapp Scribe.cs Task.Factory.StartNew(() => { try { var newProcess = _trace.Processes[childPid]; newProcess.id = childPid; newProcess.executablePath = executablePath; newProcess.commandLine = new Toolkit.Trace.CommandLine { Line = commandLine }; if (process != null) { newProcess.applicationName = process.ProcessName; newProcess.currentDirectory = string.IsNullOrEmpty(process.StartInfo.WorkingDirectory) ? currentWorkingDirectory : process.StartInfo.WorkingDirectory; // // Document environmental variables // foreach (DictionaryEntry entry in process.StartInfo.EnvironmentVariables) { var v = new Toolkit.Trace.Variable { name = entry.Key.ToString(), Value = entry.Value.ToString() }; newProcess.environment.Add(v); } // // Keep the process object around, so we know if we're done or not. // _processMap.Add(process); } if (parentPid != 0) { using (var p = GetStartedProcessById(parentPid)) { // // Move the process to its rightful spot in the process tree. // _trace.SetParentProcessId(newProcess, parentPid); } } } catch (Exception e) { Debug.Print("[Trace]"+e.Message); Debug.Print(e.StackTrace.Replace(" at","[Trace] at")); } }) Link To Source File
pubnub Pubnub.cs Task.Factory.StartNew(() => { int failureCount = 0; // check if the subscription still exists in the dictionary // if not, then end this task, otherwise, repeat. using (var handle = new System.Threading.ManualResetEventSlim(false)) { while (_subscriptions.ContainsKey(subscription.Channel)) { try { var url = PubnubRequest.BuildUrl(PubnubConfiguration.EnableSsl, "subscribe", PubnubConfiguration.SubscribeKey, subscription.Channel, "0", subscription.TimeToken.ToString()); var request = new PubnubRequest(); var json = string.Empty; request.Execute(url, out json); var result = JsonConvert.DeserializeObject>(json); #if DEBUG System.Diagnostics.Debug.WriteLine(json); #endif if (result[0] is JArray && result[0].ToString() != "[]") { // loop through each message and fire individually for (var i = 0; i < ((JArray)result[0]).Count; i++) { var message = ((JArray)result[0])[i].ToString(); if (MessageRecieved != null && !string.IsNullOrEmpty(message)) try { MessageRecieved(null, new PubNubEventArgs { Channel = subscription.Channel, Message = message }); } catch (Exception exp) { // adding this try catch because if we have multiple messages and one of // them encouters an unhandled exception it should not impact the others // or the subscription time token. System.Diagnostics.Debug.WriteLine("MessageRecievedException: " + exp.Message); } } } // update the time token lock (_sync) if (_subscriptions.ContainsKey(subscription.Channel)) _subscriptions[subscription.Channel].TimeToken = Convert.ToInt64(result[1].ToString()); // reset the failure count failureCount = 0; } catch (Exception exp) { System.Diagnostics.Debug.WriteLine("SubscriptionException: " + exp.Message); failureCount++; handle.Wait(GetWaitTimeForErrorCount(failureCount)); // rather than throwing the errors, we collect them for // periodic analysis, the idea is to enhance this with error limits // and a backoff strategy incase there is a problem with Pubnub // or the local connection to pubnub lock (_sync) if (_subscriptions.ContainsKey(subscription.Channel)) _subscriptions[subscription.Channel].Errors.Add(exp); } } } }) Link To Source File
pubnub Subscribe.cs Task.Factory.StartNew(() => { if (e.Channel == "csharp_throughput_test") { var o = JObject.Parse(e.Message); System.Diagnostics.Debug.WriteLine(o["ID"].ToString()); lock (sync) list.Remove(Convert.ToInt32(o["ID"].ToString())); if (Interlocked.Decrement(ref count) == 0) { System.Threading.Thread.Sleep(1000); handle.Set(); } } }) Link To Source File
pubnub Program.cs Task.Factory.StartNew(() => { if (e.Channel == Program.ChatChannel) { var message = JsonConvert.DeserializeObject(e.Message); if (message.FromUuid != Uuid) { switch (message.Type) { case "ping": UpdateTime(message.FromUuid); break; case "leaving": if (people.ContainsKey(message.FromUuid)) lock (sync) people.Remove(message.FromUuid); break; case "joined": if (!people.ContainsKey(message.FromUuid)) { lock (sync) people.Add(message.FromUuid, message.From); Console.WriteLine(message.From + " has joined the chat"); } UpdateTime(message.FromUuid); break; case "message": UpdateTime(message.FromUuid); Console.WriteLine(string.Format("{0} said:/n{1}", message.From, message.Message)); break; } } } }) Link To Source File
pubnub Program.cs // to keep all the other clients up to date, let's // remind them we're here every 30 seconds, otherwise // they'll forget we exist within 60 seconds Task.Factory.StartNew(() => { using (handle = new AutoResetEvent(false)) { while (Running) { // let everyone know that we're still here pubnub.Publish(Program.ChatChannel, new ChatMessage { Type = "ping", From = chatName }); // check our list of people, and if there is anyone // who hasn't checked in over 60 seconds. foreach (var kvp in peopleHistory) { if ((DateTime.Now - kvp.Value).TotalSeconds >= 60) lock (sync) if (people.ContainsKey(kvp.Key)) people.Remove(kvp.Key); } // now remove any people from the history list, who // are not in the regular list lock (sync) { var list = peopleHistory.Keys.ToList(); for (var i = 0; i < peopleHistory.Keys.Count; i++) if (!people.ContainsKey(list[i])) peopleHistory.Remove(list[i]); } handle.WaitOne(new TimeSpan(0, 0, 30)); } } }) Link To Source File
ProjectExtensions.Azure.ServiceBus AzureBusReceiver.cs Task.Factory.StartNew(() => { //HACK find better way to wait for a cancel request so we are not blocking. logger.Info("CancelSubscription Deleting {0}", value.SubscriptionName); for (int i = 0; i < 100; i++) { if (!subscription.Data.Cancelled) { Thread.Sleep(1000); } else { break; } } if (configurationFactory.NamespaceManager.SubscriptionExists(topic.Path, value.SubscriptionName)) { var filter = new SqlFilter(string.Format(TYPE_HEADER_NAME + " = '{0}'", value.MessageType.FullName.Replace('.', '_'))); retryPolicy.ExecuteAction(() => configurationFactory.NamespaceManager.DeleteSubscription(topic.Path, value.SubscriptionName)); logger.Info("CancelSubscription Deleted {0}", value.SubscriptionName); } }) Link To Source File
IrcSharp Client.cs Task.Factory.StartNew(RecvStart) Link To Source File
IrcSharp IrcServer.cs Task.Factory.StartNew(ProcessReadQueue) Link To Source File
IrcSharp IrcServer.cs Task.Factory.StartNew(ProcessSendQueue) Link To Source File
IrcSharp MainService.cs Task.Factory.StartNew(RunServer) Link To Source File
preprompt-parallel BinaryTree.cs Task.Factory.StartNew(() => WalkParTpl(root.Left, action)) Link To Source File
preprompt-parallel BinaryTree.cs Task.Factory.StartNew(() => WalkParTpl(root.Right, action)) Link To Source File
preprompt-parallel Cancellation.cs Task.Factory.StartNew(() => { var token = cts.Token; // // The callback is executed in the thread activating cancellation. // using (token.Register(() => Console.WriteLine("Thread {0}: cancellation requested.", Thread.CurrentThread.ManagedThreadId))) { do { Thread.Yield(); } while (!token.IsCancellationRequested); Console.WriteLine("Thread {0}: Task cancelled.", Thread.CurrentThread.ManagedThreadId); throw new OperationCanceledException(token); } }, cts.Token) Link To Source File
preprompt-parallel Exceptions.cs Task.Factory.StartNew(() => { throw new Exception("Some exception."); }) Link To Source File
preprompt-parallel Exceptions.cs Task.Factory.StartNew(() => { Task.Factory.StartNew(() => { throw new Exception("Child faulting."); }, TaskCreationOptions.AttachedToParent); }) Link To Source File
preprompt-parallel Exceptions.cs Task.Factory.StartNew(() => { for (int i = 0; i < 5; i++) { int x = i; Task.Factory.StartNew(() => { throw new Exception(string.Format("Child {0} faulting.", x)); }, TaskCreationOptions.AttachedToParent); } throw new Exception("Parent faulting."); }) Link To Source File
preprompt-parallel Exceptions.cs Task.Factory.StartNew(() => { for (int i = 0; i < 2; i++) { int x = i; Task.Factory.StartNew(() => { for (int j = 0; j < 2; j++) { int y = j; Task.Factory.StartNew(() => { throw new Exception(string.Format("Grandchild {0} faulting.",y)); }, TaskCreationOptions.AttachedToParent); } throw new Exception(string.Format("Child {0} faulting", x)); }, TaskCreationOptions.AttachedToParent); } throw new Exception("Parent faulting."); }) Link To Source File
preprompt-parallel Exceptions.cs Task.Factory.StartNew(() => { Task.Factory.StartNew(() => { throw new Exception("Child faulting."); }, TaskCreationOptions.AttachedToParent); throw new Exception("Parent faulting."); }) Link To Source File
preprompt-parallel Exceptions.cs Task.Factory.StartNew(() => { var child = Task.Factory.StartNew(() => { throw new Exception("Child faulting."); }, TaskCreationOptions.AttachedToParent); try { child.Wait(); } catch { } throw new Exception("Parent faulting."); }) Link To Source File
preprompt-parallel ParallelFor.cs Task.Factory.StartNew(() => { for (int i = start; i < end; i++) { body(i); } }) Link To Source File
preprompt-parallel ParallelFor.cs Task.Factory.StartNew(() => { int i; while ((i = Interlocked.Increment(ref index) - 1) < exclusiveTo) { body(i); } }) Link To Source File
preprompt-parallel ParallelFor.cs Task.Factory.StartNew(taskReplicaDelegate) Link To Source File
preprompt-parallel SortExtensions.cs Task.Factory.StartNew(() => QuickSortPar(a, l, m - 1)) Link To Source File
preprompt-parallel SortExtensions.cs Task.Factory.StartNew(() => quicksort_internal2(a, l, m - 1, depth - 1)) Link To Source File
preprompt-parallel SortExtensions.cs Task.Factory.StartNew(() => quicksort_internal3(a, l, m - 1, state)) Link To Source File
ravendb ReplicationInformer.cs Task.Factory.StartNew(() => RefreshReplicationInformation(serverClient)) Link To Source File
ravendb ConflictsWithIIS.cs Task.Factory.StartNew(() => DoInsert(store, copy)) Link To Source File
ravendb ConflictsWithIIS.cs Task.Factory.StartNew(() => DoInefficientInsert(store.Url, copy)) Link To Source File
ravendb ConflictsWithRemote.cs Task.Factory.StartNew(() => DoInsert(store, copy)) Link To Source File
ravendb ConflictsWithRemote.cs Task.Factory.StartNew(() => DoInefficientInsert(server.Database.Configuration.ServerUrl, copy)) Link To Source File
ravendb ManyDocumentsViaDTC.cs Task.Factory.StartNew(() => { using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew)) { // Promote the transaction System.Transactions.Transaction.Current.EnlistDurable(DummyEnlistmentNotification.Id, new DummyEnlistmentNotification(), EnlistmentOptions.None); using (var session = store.OpenSession()) { session.Store(new TestDocument()); session.SaveChanges(); } scope.Complete(); } }) Link To Source File
ravendb ProcessDriver.cs Task.Factory.StartNew(() => { string line; while ((line = _process.StandardOutput.ReadLine()) != null) { output.Add(line); } }) Link To Source File
ravendb ProcessDriver.cs Task.Factory.StartNew(() => { string line; while ((line = _process.StandardError.ReadLine()) != null) { error.Add(line); } }) Link To Source File
ravendb ProcessDriver.cs Task.Factory.StartNew(() => { while (_process.HasExited == false) { _process.StandardInput.WriteLine(input.Take()); } }) Link To Source File
ReFrameworker---Old-Spice-Edition MainWindowViewModel.cs Task.Factory.StartNew(() => { _rootkitService.InjectRootkit(_loadedItem.OriginalItem, _progress.Update); if (MessageBox.Show("Generate batch deployer?", "Deployer", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1) == DialogResult.Yes) { _rootkitService.CreateDeploymentKit(_loadedItem.OriginalItem, _progress.Update); } }) Link To Source File
Golf GameEngine.cs Task.Factory.StartNew(RunShotToCompletion) Link To Source File
MonoMobile.Views UrlImageStore.cs factory.StartNew(() => { try { var data = NSData.FromUrl(NSUrl.FromString(url)); if (data == null) { Console.WriteLine("UrlImageStore: No data for URL: " + url); return; } var img = UIImage.LoadFromData(data); img = ProcessImage(id, img); AddToCache(id, img); notify.UrlImageUpdated(id, img); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }) Link To Source File
NewWestlink LogProcessor.cs Task.Factory.StartNew(() => { test = "RQ Test"; }) Link To Source File
NServieBus.Xms XmsConsumerProviderTest.cs taskFactory.StartNew( () => { using(var consumer = provider.GetConsumer(destination)) { var message = consumer.ReceiveNoWait(); if (message != null) Interlocked.Increment(ref actual); } }) Link To Source File
NServieBus.Xms PerformanceTest.cs taskFactory.StartNew( () => { using(var scope = new TransactionScope(TransactionScopeOption.Required)) { var producer = provider.GetProducer(destination); var msg = producer.CreateTextMessage(); msg.Text = "Hello XMS message." + DateTime.Now; producer.Send(msg); scope.Complete(); } }) Link To Source File
NServieBus.Xms PerformanceTest.cs taskFactory.StartNew( () => { var producer = provider.GetProducer(destination); var msg = producer.CreateTextMessage(); msg.Text = "Hello XMS message." + DateTime.Now; producer.Send(msg); }) Link To Source File
NServieBus.Xms XmsProducerProviderTest.cs taskFactory.StartNew( () => { using(var scope = new TransactionScope(TransactionScopeOption.Required)) { provider.SendTestMessage(destination); scope.Complete(); } }) Link To Source File
SLRSyncUploader PicoDelta.cs Task.Factory.StartNew(() => { var fileHashes = fileProcessor.GetHashesForFile(filePath, progressReporter, config); using (var ms = new MemoryStream()) { var binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(ms, fileHashes); ds.FileSignatures.AddObject(new FileSignature() { FileId = fileId, FilePath = filePath, Signature = ms.ToArray() }); } ds.SaveChanges(); }) Link To Source File
RWCM-Demo Global.asax.cs Task.Factory.StartNew(() => { using (var scope = _Container.BeginLifetimeScope()) { var db = scope.Resolve(); WebRequestLog newLogItem = new WebRequestLog(); newLogItem.Referer = referer; newLogItem.RequestUrl = requestUrl; newLogItem.UserAgent = userAgent; newLogItem.UserHostAddress = userHostAddress; newLogItem.UserName = userName; db.WebRequestLogs.InsertOnSubmit(newLogItem); db.SubmitChanges(); } }) Link To Source File
SimpleConcurrency Schedulers.cs Task.Factory.StartNew(action) Link To Source File
yessql Session.cs Task.Factory.StartNew(() => { Reduce(); _transaction.Commit(); }) Link To Source File
RaptorJS RaptorServer.cs Task.Factory.StartNew(() => this.HandleRequest(httpContext)) Link To Source File
OpenStory Synchronizer.Synchronized.cs Task.Factory.StartNew(this.GetAction(objectAction)) Link To Source File
Roger General_federation_tests.cs Task.Factory.StartNew(() => SubscribeAndReceiveOnce(Helpers.CreateConnectionToSecondaryVirtualHostOnAlternativePort())) Link To Source File
Roger General_federation_tests.cs Task.Factory.StartNew(() => PublishOnce(Helpers.CreateConnection())) Link To Source File
Roger General_federation_tests.cs Task.Factory.StartNew(() => SubscribeAndReceiveOnce(Helpers.CreateConnection())) Link To Source File
Roger General_federation_tests.cs Task.Factory.StartNew(() => PublishOnce(Helpers.CreateConnectionToSecondaryVirtualHostOnAlternativePort())) Link To Source File
Roger ResequencingDeduplicationFilterTest.cs Task.Factory.StartNew(() => { foreach (var m in sut.Filter(input.Cast(), model)) output.Enqueue(m); }) Link To Source File
OISCVM KeyboardDevice.cs Task.Factory.StartNew(() => { while (true) { ConsoleKeyInfo data = Console.ReadKey(true); char charData = data.KeyChar; _memoryBus.WriteData(1048319, charData); _memoryBus.WriteData(1048431, 1); } }) Link To Source File
OISCVM InterruptHandler.cs Task.Factory.StartNew(() => { hardwareIrq.Interrupt(hardwareIrq, e.MemoryLocation, e.NewValue); }) Link To Source File
codegallery ServiceWrapper.cs Task.Factory.StartNew(() => ServiceCall(item)) Link To Source File
projects StubComponent.cs Task.Factory.StartNew(() => DoWork(heartbeat, taskIndex, finalTaskIndex)) Link To Source File
projects HeartbeatTest.cs Task.Factory.StartNew(() => DoWork(heartbeat, taskIndex, finalTaskIndex)) Link To Source File
Merchant-Editor ItemSelector.xaml.cs _factory.StartNew(() => _results.AddRange(DataProvider.Items)) Link To Source File
Merchant-Editor ItemSelector.xaml.cs Task.Factory.StartNew(UpdateQuery) Link To Source File
Merchant-Editor ItemSelector.xaml.cs _factory.StartNew(() => _results.Clear()) Link To Source File
Merchant-Editor ItemSelector.xaml.cs Task.Factory.StartNew(UpdateItems) Link To Source File
Merchant-Editor ItemSelector.xaml.cs _factory.StartNew(UpdateGrid) Link To Source File
sones IncomingEdgeSorter.cs Task.Factory.StartNew(() => SortChunk(_chunks[location])) Link To Source File
spring-net-amqp RabbitTemplateIntegrationTests.cs Task.Factory.StartNew(() => { Message insidemessage = null; for (int i = 0; i < 10; i++) { insidemessage = template.Receive(); if (insidemessage != null) { break; } Thread.Sleep(100); } Assert.IsNotNull(insidemessage, "No message received"); template.Send(insidemessage.MessageProperties.ReplyTo, insidemessage); return insidemessage; }) Link To Source File
spring-net-amqp RabbitTemplateIntegrationTests.cs Task.Factory.StartNew(() => { Message internalmessage = null; for (int i = 0; i < 10; i++) { internalmessage = template.Receive(ROUTE); if (internalmessage != null) { break; } Thread.Sleep(100); } Assert.IsNotNull(internalmessage, "No message received"); template.Send(internalmessage.MessageProperties.ReplyTo, internalmessage); return internalmessage; }) Link To Source File
spring-net-amqp RabbitTemplateIntegrationTests.cs Task.Factory.StartNew(() => { Message internalmessage = null; for (var i = 0; i < 10; i++) { internalmessage = template.Receive(ROUTE); if (internalmessage != null) { break; } Thread.Sleep(100); } Assert.IsNotNull(internalmessage, "No message received"); template.Send(internalmessage.MessageProperties.ReplyTo, internalmessage); return internalmessage; }) Link To Source File
spring-net-amqp RabbitTemplateIntegrationTests.cs Task.Factory.StartNew(() => { Message message = null; for (var i = 0; i < 10; i++) { message = template.Receive(); if (message != null) { break; } Thread.Sleep(100); } Assert.IsNotNull(message, "No message received"); template.Send(message.MessageProperties.ReplyTo, message); return (string)template.MessageConverter.FromMessage(message); }) Link To Source File
spring-net-amqp RabbitTemplateIntegrationTests.cs Task.Factory.StartNew(() => { Message message = null; for (var i = 0; i < 10; i++) { message = template.Receive(ROUTE); if (message != null) { break; } Thread.Sleep(100); } Assert.IsNotNull(message, "No message received"); template.Send(message.MessageProperties.ReplyTo, message); return (string)this.template.MessageConverter.FromMessage(message); }) Link To Source File
spring-net-amqp RabbitTemplateIntegrationTests.cs Task.Factory.StartNew(() => { Message message = null; for (var i = 0; i < 10; i++) { message = template.Receive(ROUTE); if (message != null) { break; } Thread.Sleep(100); } Assert.IsNotNull(message, "No message received"); template.Send(message.MessageProperties.ReplyTo, message); return (string)this.template.MessageConverter.FromMessage(message); }) Link To Source File
spring-net-amqp MessageListenerContainerRetryIntegrationTests.cs Task.Factory.StartNew(() => { while (container.ActiveConsumerCount > 0) { try { Thread.Sleep(100); } catch (ThreadInterruptedException e) { if (latch.CurrentCount > 0) latch.Signal(); Thread.CurrentThread.Interrupt(); return; } } for (var i = 0; i < count; i++) { if (latch.CurrentCount > 0) latch.Signal(); } }) Link To Source File
FluentAutomation AutomationProvider.cs System.Threading.Tasks.Task.Factory.StartNew(() => { // Dirty I know.. Need to guarantee the dialog opens before we start sending key events. int sleepTime = 0; switch (_browserType) { case BrowserType.Firefox: sleepTime = 1000; break; case BrowserType.Chrome: sleepTime = 1500; break; } Thread.Sleep(sleepTime); CommandManager.SendString(fileName + "~"); }, System.Threading.Tasks.TaskCreationOptions.LongRunning) Link To Source File
backgrounded DaemonSpawner.cs Task.Factory.StartNew(() => { var payloads = daemon.Payloads; var objectHandle = Activator.CreateInstance(daemon.AssemblyName, daemon.TypeName); var o = objectHandle.Unwrap(); var method = o.GetType().GetMethod(daemon.MethodName); var parameters = GetParameters(payloads); logger.Info(typeof(Background), "Running daemon " + daemon.MethodName); method.Invoke(o, parameters); }) Link To Source File
backgrounded DelayedJobSpawner.cs Task.Factory.StartNew(() => { var payloads = job.Payloads; var objectHandle = Activator.CreateInstance(job.AssemblyName, job.TypeName); var o = objectHandle.Unwrap(); var method = o.GetType().GetMethod(job.MethodName); var parameters = GetParameters(payloads); logger.Info(typeof(Background), "Running delayed job: " + job.MethodName); method.Invoke(o, parameters); }) Link To Source File
backgrounded ScheduledJobSpawner.cs Task.Factory.StartNew(() => { var payloads = scheduledJob.Payloads; var objectHandle = Activator.CreateInstance( scheduledJob.AssemblyName, scheduledJob.TypeName); var o = objectHandle.Unwrap(); var method = o.GetType().GetMethod(scheduledJob.MethodName); var parameters = GetParameters(payloads); logger.Info(typeof(Background), "Running scheduled job: " + scheduledJob.MethodName); method.Invoke(o, parameters); }) Link To Source File
WS-Man.Net HttpListenerTransferEndpoint.cs Task.Factory.StartNew(AcceptingLoop) Link To Source File
WS-Man.Net HttpListenerTransferEndpoint.cs Task.Factory.StartNew(() => TryHandleRequest(ctx)) Link To Source File
talifun-commander ExecuteBoxNetUploaderWorkflowMessageHandlerBase.cs Task.Factory.StartNew(() => { }) Link To Source File
talifun-commander ExecuteDropBoxUploaderWorkflowMessageHandlerBase.cs Task.Factory.StartNew(() => { }) Link To Source File
talifun-commander ExecuteFlickrUploaderWorkflowMessageHandlerBase.cs Task.Factory.StartNew(() => { }) Link To Source File
talifun-commander ExecutePicasaUploaderWorkflowMessageHandlerBase.cs Task.Factory.StartNew(()=>{}) Link To Source File
talifun-commander ExecuteYouTubeUploaderWorkflowMessageHandlerBase.cs Task.Factory.StartNew(()=>{}) Link To Source File
snippets DataParallelism.cs // Run a task so that we can cancel from another thread. Task.Factory.StartNew(() => { Thread.Sleep(1000); cts.Cancel(); Console.WriteLine("Loop is canceled by {0}", Thread.CurrentThread.ManagedThreadId); }) Link To Source File
snippets TPLTests.cs Task.Factory.StartNew(() => Console.WriteLine("Hello World")) Link To Source File
snippets TPLTests.cs Task.Factory.StartNew(() => { Console.WriteLine("Outer task beginning."); var child = Task.Factory.StartNew(() => { Thread.SpinWait(50000); Console.WriteLine("Detached task completed."); }); }) Link To Source File
snippets TPLTests.cs Task.Factory.StartNew(() => { Thread.SpinWait(50000); Console.WriteLine("Detached task completed."); }) Link To Source File
snippets TPLTests.cs Task.Factory.StartNew(() => { Console.WriteLine("Parent task beginning."); var child = Task.Factory.StartNew(() => { Thread.SpinWait(50000); Console.WriteLine("Attached child completed."); }, TaskCreationOptions.AttachedToParent); }) Link To Source File
ExpressUnit TestMethodViewModel.cs factory.StartNew((obj) => Run(obj as TestMethod), method) Link To Source File
artemis_CSharp ParallelEntityProcessingSystem.cs factory.StartNew( () => { for (int i = initial; i > initial - perThread && i >= 0; i--) { Process(ents[i]); } } ) Link To Source File
artemis_CSharp SystemManager.cs factory.StartNew( () => { es.Process(); } ) Link To Source File
dwarrowdelf Player.cs // XXX creating IP engine takes some time. Do it in the background. Race condition with IP msg handlers System.Threading.Tasks.Task.Factory.StartNew(delegate { m_ipRunner = new IPRunner(m_world, Send); }) Link To Source File
dwarrowdelf MapControl.cs Task.Factory.StartNew(() => m_result = AStarFinder.Find(this, src, this.SrcPos, dst, this.DstPos)) Link To Source File
torshify-client BackdropService.cs Task.Factory.StartNew(() => StartDownloading(artistName, downloadFolder, foundBackdrop, didNotFindBackdrop)) Link To Source File
torshify-client KenBurnsBackgroundEffect.cs Task.Factory.StartNew(() => { try { BitmapImage bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.DecodePixelHeight = 800; bitmapImage.StreamSource = new FileStream( backdropFile, FileMode.Open, FileAccess.Read); bitmapImage.EndInit(); bitmapImage.Freeze(); _dispatcher.BeginInvoke( new Action(DisplayBackgroundImage), bitmapImage); } catch (Exception e) { _logger.Log(e.ToString(), Category.Exception, Priority.Medium); } }) Link To Source File
torshify-client LatestNewsTabItemViewModel.cs Task.Factory.StartNew(() => FindNewsForArtist(model)) Link To Source File
torshify-client DiscoverViewModel.cs Task.Factory.StartNew(() => { using (var session = new EchoNestSession(EchoNestModule.ApiKey)) { var styles = session.Query().Execute(ListTermsType.Style); var moods = session.Query().Execute(ListTermsType.Mood); if (styles.Status.Code == ResponseCode.Success) { Styles = new ListCollectionView(styles.Terms.Select(s => new TermModel{Name = s.Name}).ToArray()); } if (moods.Status.Code == ResponseCode.Success) { Moods = new ListCollectionView(moods.Terms.Select(s => new TermModel{Name = s.Name}).ToArray()); } } }) Link To Source File
torshify-r4dio BackdropService.cs Task.Factory.StartNew(() => StartDownloading(artistName, downloadFolder, foundBackdrop, didNotFindBackdrop)) Link To Source File
torshify-r4dio RadioNowPlayingViewModel.cs Task.Factory.StartNew(() => MoveToNext(CancellationToken.None)) Link To Source File
torshify-r4dio RadioNowPlayingViewModel.cs Task.Factory.StartNew(() => MoveToNext(CancellationToken.None)) Link To Source File
torshify-r4dio TrackDJResultsViewModel.cs Task.Factory.StartNew(() => { List allTracks = new List(); IsLoading = true; try { using (EchoNestSession session = new EchoNestSession(EchoNestConstants.ApiKey)) { var arg = setup.CreateSearchArgument(); arg.Bucket = SongBucket.ArtistLocation; var result = session.Query().Execute(arg); if (result == null) { result = session.Query().Execute(arg); } if (result != null && result.Status.Code == ResponseCode.Success) { var artists = result.Songs.GroupBy(s => s.ArtistName); Parallel.ForEach(artists, artist => { var tracks = _radio.GetTracksByArtist(artist.Key, 0, 100); foreach (var songBucketItem in artist) { var track = tracks.FirstOrDefault( t => t.Name.Equals(songBucketItem.Title, StringComparison. InvariantCultureIgnoreCase)); if (track != null) { track.ExtraData.Terms = null; Task .Factory .StartNew(FindArtistInformation, Tuple.Create(track, songBucketItem)); allTracks.Add(track); Application.Current.Dispatcher.BeginInvoke( new Action(_tracks.Add), track); } } }); } } } catch(Exception ex) { Console.WriteLine(ex.Message); } IsLoading = false; return allTracks; }) Link To Source File
torshify-r4dio ArtistBrowseViewModel.cs Task.Factory .StartNew(state => { var artist = (ArtistModel)state; using (EchoNestSession session = new EchoNestSession(EchoNestConstants.ApiKey)) { var profile = session.Query().Execute( artist.Name, ArtistBucket.News | ArtistBucket.Images | ArtistBucket.Biographies | ArtistBucket.Blogs | ArtistBucket.Video); if (profile.Status.Code == ResponseCode.Success) { artist.News = profile.Artist.News; artist.Images = profile.Artist.Images; artist.Image = profile.Artist.Images.FirstOrDefault(); artist.Biographies = profile.Artist.Biographies; artist.Biography = profile.Artist.Biographies.FirstOrDefault(); artist.Blogs = profile.Artist.Blogs; artist.Videos = profile.Artist.Videos; } } }, artistModel) Link To Source File
torshify-r4dio AutoCompleteViewModel.cs Task.Factory .StartNew(() => { using (EchoNestSession session = new EchoNestSession(EchoNestConstants.ApiKey)) { var response = session .Query() .Execute(searchText); if (response.Status.Code == ResponseCode.Success) { return response.Artists.Select(t => t.Name); } } return new string[0]; }) Link To Source File
torshify-r4dio SimilarArtistsRadioStationViewModel.cs Task.Factory .StartNew(() => { try { using (EchoNestSession session = new EchoNestSession(EchoNestConstants.ApiKey)) { var response = session .Query() .Execute(searchText); if (response.Status.Code == ResponseCode.Success) { return response.Artists.Select(t => t.Name); } } } catch (Exception e) { Console.WriteLine(e); } return new string[0]; }) Link To Source File
torshify-r4dio EightTracksRadioStationViewModel.cs Task.Factory .StartNew(() => { using (var session = new EightTracksSession(EightTracksRadioStation.ApiKey)) { TagsResponse response = session.Query().Execute(1, text); return response.Tags.Select(t => t.Name); } }) Link To Source File
torshify-r4dio EightTracksRadioStationViewModel.cs Task.Factory.StartNew(() => { using (var session = new EightTracksSession(EightTracksRadioStation.ApiKey)) { if (SearchType == EightTracksSearchType.Tag) { var response = session.Query().GetMix(tag: text); return response.Mixes; } else { var response = session.Query().GetMix(filter: text); return response.Mixes; } } }) Link To Source File
torshify-r4dio EightTracksRadioStationViewModel.cs Task.Factory.StartNew(() => { using (var session = new EightTracksSession(EightTracksRadioStation.ApiKey)) { var response = session.Query().GetMix(sorting: Mixes.Sort.Recent); return response.Mixes; } }) Link To Source File
torshify-r4dio GroovesharkRadioTrackSource.cs Task.Factory.StartNew(() => { try { Session = new GroovesharkSession(); Session.Connect(); } catch (Exception e) { _logger.Log("Error while connecting to Grooveshark. " + e, Category.Exception, Priority.Medium); } }) Link To Source File
torshify-r4dio OrigoConnectionManager.cs Task.Factory.StartNew(() => { AppDomainSetup setup = new AppDomainSetup(); setup.ApplicationName = "Spotify"; setup.ApplicationBase = Environment.CurrentDirectory; setup.PrivateBinPath = Path.Combine("Modules", "Spotify"); setup.PrivateBinPathProbe = "true"; AppDomain origoDomain = AppDomain.CreateDomain("OrigoDomain", null, setup); AppDomain.CurrentDomain.AssemblyResolve += OrigoDomainOnAssemblyResolve; OrigoBootstrapper host = origoDomain.CreateInstanceAndUnwrap( typeof (OrigoBootstrapper).Assembly.FullName, "Torshify.Origo.OrigoBootstrapper") as OrigoBootstrapper; AppDomain.CurrentDomain.AssemblyResolve -= OrigoDomainOnAssemblyResolve; if (host != null) { InitializeCommandLineOptions(Environment.GetCommandLineArgs(), host); host.Run(); } }) Link To Source File
torshify-server App.xaml.cs Task.Factory.StartNew(() => { AppDomainSetup setup = new AppDomainSetup(); setup.ApplicationName = "Spotify"; setup.ApplicationBase = Environment.CurrentDirectory; AppDomain origoDomain = AppDomain.CreateDomain("OrigoDomain", null, setup); AppDomain.CurrentDomain.AssemblyResolve += OrigoDomainOnAssemblyResolve; OrigoBootstrapper host = origoDomain.CreateInstanceAndUnwrap( typeof(OrigoBootstrapper).Assembly.FullName, "Torshify.Origo.OrigoBootstrapper") as OrigoBootstrapper; AppDomain.CurrentDomain.AssemblyResolve -= OrigoDomainOnAssemblyResolve; if (host != null) { host.Run(); } }) Link To Source File
Lokad-Cqrs-Extensions SnapshottingProcess.cs Task.Factory.StartNew(() => { while (!token.IsCancellationRequested) { CreateSnapshots(eventStore.GetStreamsToSnapshot(threshold).ToArray()); token.WaitHandle.WaitOne(checkInterval); } }) Link To Source File
alaris PublicMessageHandler.cs Task.Factory.StartNew(() => { var urlsin = Utilities.GetUrls(smsg); if (urlsin.Count <= 0) return; try { Parallel.ForEach(urlsin, url => Utilities.HandleWebTitle(chan, url)); return; } catch (Exception ex) { Log.Error("Invalid webpage address: {0}", ex.Message); //_connection.Sender.PublicMessage(chan, IrcConstants.Red + "Invalid address."); return; } }) Link To Source File
alaris AlarisBase.cs Task.Factory.StartNew(() => { Log.Info("Starting Identd service"); Identd.Start(_nick); }) Link To Source File
alaris AlarisBase.cs Task.Factory.StartNew(() => _manager.Run()) Link To Source File
alaris AlarisBase.cs Task.Factory.StartNew(() => { Log.Info("Setting up commands"); CommandManager.CommandPrefix = "@"; CommandManager.CreateMappings(); }) Link To Source File
alaris AlarisBase.cs Task.Factory.StartNew(ServiceManager.StartServices) Link To Source File
alaris AlarisBase.cs Task.Factory.StartNew(() => CommandManager.HandleCommand(user, channel, message)) Link To Source File
vcap-dotnet NodeBase.cs credentials.ServiceWorkFactory.StartNew( () => { try { ServiceCredentials credential = Provision(plan, credentials); credential.NodeId = this.nodeId; response.Credentials = credential; Logger.Debug( Strings.OnProvisionSuccessDebugLogMessage, ServiceDescription(), msg, response.SerializeToJson()); NodeNats.Publish(reply, null, EncodeSuccess(response)); } catch (Exception ex) { Logger.Warning(ex.ToString()); NodeNats.Publish(reply, null, EncodeFailure(response)); } }) Link To Source File
vcap-dotnet NodeBase.cs credentials.ServiceWorkFactory.StartNew( () => { try { ServiceCredentials[] bindings = unprovision_req.Bindings; bool result = this.Unprovision(name, bindings); if (result) { this.NodeNats.Publish(reply, null, EncodeSuccess(response)); } else { this.NodeNats.Publish(reply, null, EncodeFailure(response)); } } catch (Exception ex) { Logger.Warning(ex.ToString()); NodeNats.Publish(reply, null, EncodeFailure(response, ex)); } }) Link To Source File
vcap-dotnet NodeBase.cs nameCredentials.ServiceWorkFactory.StartNew( () => { try { Dictionary bind_opts = bind_message.BindOptions; ServiceCredentials credentials = bind_message.Credentials; response.Credentials = this.Bind(name, bind_opts, credentials); NodeNats.Publish(reply, null, EncodeSuccess(response)); } catch (Exception ex) { Logger.Warning(ex.ToString()); NodeNats.Publish(reply, null, EncodeFailure(response, ex)); } }) Link To Source File
vcap-dotnet NodeBase.cs unbind_req.Credentials.ServiceWorkFactory.StartNew( () => { try { bool result = this.Unbind(unbind_req.Credentials); if (result) { this.NodeNats.Publish(reply, null, EncodeSuccess(response)); } else { this.NodeNats.Publish(reply, null, EncodeFailure(response)); } } catch (Exception ex) { Logger.Warning(ex.ToString()); NodeNats.Publish(reply, null, EncodeFailure(response, ex)); } }) Link To Source File
vcap-dotnet NodeBase.cs prov_cred.ServiceWorkFactory.StartNew( () => { try { string instance = prov_cred.Name; string file_path = this.GetMigrationFolder(instance); Directory.CreateDirectory(file_path); bool result = this.DisableInstance(prov_cred, binding_creds); if (result) { result = this.DumpInstance(prov_cred, binding_creds, file_path); } NodeNats.Publish(reply, null, result.ToString()); } catch (Exception ex) { Logger.Warning(ex.ToString()); } }) Link To Source File
vcap-dotnet NodeBase.cs prov_cred.ServiceWorkFactory.StartNew( () => { try { this.EnableInstance(ref prov_cred, ref binding_creds_hash); // Update node_id in provision credentials.. prov_cred.NodeId = this.nodeId; credentials[0] = prov_cred; credentials[1] = binding_creds_hash; NodeNats.Publish(reply, null, JsonConvertibleObject.SerializeToJson(credentials)); } catch (Exception ex) { Logger.Warning(ex.ToString()); } }) Link To Source File
vcap-dotnet NodeBase.cs prov_cred.ServiceWorkFactory.StartNew( () => { try { string instance = prov_cred.Name; Directory.Delete(this.GetMigrationFolder(instance), true); NodeNats.Publish(reply, null, "true"); } catch (Exception ex) { Logger.Warning(ex.ToString()); } }) Link To Source File
vcap-dotnet NodeBase.cs // We're running the unbind on the same thread that other stuff is running for this service instance, so we don't get race conditions; need to wait though, so we have a result status credential.ServiceWorkFactory.StartNew( () => { try { Logger.Debug(Strings.PurgeOrphanUnbindBindingDebugLogMessage, credential.SerializeToJson()); ret = ret && this.Unbind(credential); } catch (Exception ex) { Logger.Debug(Strings.PurgeOrphanUnbindBindingErrorLogMessage, credential.SerializeToJson(), ex.ToString()); } }) Link To Source File
vcap-dotnet NodeBase.cs prov_cred.ServiceWorkFactory.StartNew( () => { try { string instance = prov_cred.Name; string file_path = this.GetMigrationFolder(instance); bool result = this.ImportInstance(prov_cred, binding_creds, file_path, plan); NodeNats.Publish(reply, null, result.ToString()); } catch (Exception ex) { Logger.Warning(ex.ToString()); } }) Link To Source File
vcap-dotnet Reactor.cs this.messageCallbackFactory.StartNew( () => { if (!this.subscriptions.ContainsKey(sid)) { return; } nantsSubscription.Callback(msg, replyMessage, nantsSubscription.Subject); }) Link To Source File
Xtal ConsistencyTests.cs Task.Factory.StartNew(() => d1(1000, 1000, 1500)) Link To Source File
Xtal ConsistencyTests.cs Task.Factory.StartNew(() => d1(3000, 1000, 3500)) Link To Source File
Xtal ConsistencyTests.cs Task.Factory.StartNew(() => d1(5000, 1000, 5500)) Link To Source File
Xtal ConsistencyTests.cs Task.Factory.StartNew(() => d1(7000, 1000, 7500)) Link To Source File
Xtal LoadTest.cs Task.Factory.StartNew(() => mtTest(ss)) Link To Source File
MadCow UpdaterProcedure.cs Task.Factory.StartNew(() => z.ExtractZip(Path.GetTempPath() + @"/MadCow.zip", Path.GetTempPath() + @"/" + @"MadCow/",null)) Link To Source File
cs160 KinectSettings.xaml.cs Task.Factory.StartNew( () => { try { // Check for not null and running if ((this.Kinect != null) && this.Kinect.IsRunning) { // We must wait at least 1 second, and call no more frequently than 15 times every 20 seconds // So, we wait at least 1350ms afterwards before we set backgroundUpdateInProgress to false. this.Kinect.ElevationAngle = angleToSet; this.lastSetSensorAngle = angleToSet; Thread.Sleep(1350); } } finally { this.backgroundUpdateInProgress = false; } }) Link To Source File
WindowsGame WorkspaceViewModel.cs System.Threading.Tasks.Task.Factory.StartNew(() => { //var type = pluginManager.GameRegistry.GameTypes[0]; //var game = Activator.CreateInstance(type) as Microsoft.Xna.Framework.Game; //Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory; //game.Run(); //var setup = new AppDomainSetup(); //setup.ApplicationBase = @"C:/Documents and Settings/willcraftia/My Documents/Visual Studio 2010/Projects/WindowsGame8/WindowsGame8/bin/x86/Debug"; //setup.ApplicationName = "WindowsGame8"; //setup.PrivateBinPath = @"C:/Documents and Settings/willcraftia/My Documents/Visual Studio 2010/Projects/WindowsGame8/WindowsGame8/bin/x86/Debug"; //setup.ShadowCopyFiles = "false"; //var evidence = new System.Security.Policy.Evidence(AppDomain.CurrentDomain.Evidence); //var gameDomain = AppDomain.CreateDomain("GameDomain", evidence, setup); //System.IO.Directory.SetCurrentDirectory(@"C:/Documents and Settings/willcraftia/My Documents/Visual Studio 2010/Projects/WindowsGame8/WindowsGame8/bin/x86/Debug"); //gameDomain.ExecuteAssembly(@"C:/Documents and Settings/willcraftia/My Documents/Visual Studio 2010/Projects/WindowsGame8/WindowsGame8/bin/x86/Debug/WindowsGame8.exe"); }) Link To Source File
Robot-Sorter-Deluxe ScorBotScript.cs Task.Factory.StartNew(() => ExecuteScript(script)) Link To Source File
Robot-Sorter-Deluxe ScorBotScript.cs Task.Factory.StartNew(() => ExecuteScript(reader)) Link To Source File
Robot-Sorter-Deluxe ScorBotScript.cs Task.Factory.StartNew(() => CheckScript(script)) Link To Source File
Robot-Sorter-Deluxe ScorBotScript.cs Task.Factory.StartNew(() => CheckScript(reader)) Link To Source File
monotouch-samples RootViewController.cs Task.Factory.StartNew (() => { }) Link To Source File
Ani-Me Helper.cs System.Threading.Tasks.Task.Factory.StartNew(act) Link To Source File
Rummage MainWindow.xaml.cs Task.Factory.StartNew(() => { prepareAndSearch(request, search); this.Dispatcher.BeginInvoke(new Action(() => updateStatus("") ) , null); }, token) Link To Source File
Rummage SearchFilesystem.cs Task.Factory.StartNew(() => { List matchesInThisFile = new List(); matchesInThisFile = searchFile(regexes, url); Matches.AddRange(matchesInThisFile); OnFileSearched(new ItemSearchedEventArgs(url, matchesInThisFile, ItemNumber, SearchRequest.Urls.Count)); }, cancellationToken) Link To Source File
RI-Project MainForm.cs Task.Factory.StartNew(() => { stats.Proceed(openFileDialog1.FileName); }) Link To Source File
RI-Project MainForm.cs Task.Factory.StartNew(() => { statsXML.Proceed(dlg.SelectedPath, 200); statsXML.B = 0.5; statsXML.K = 1; }) Link To Source File
RI-Project Statistics.cs Task.Factory.StartNew(() => { StreamReader fs = new StreamReader(url); while (!fs.EndOfStream) { ProceedOneLine(fs.ReadLine()); } fs.Close(); }) /*.ContinueWith(_ => ShowStats(GlobalStatistic))*/ Link To Source File
msgpack-rpc-cli AsyncServiceInvoker`1.cs Task.Factory.StartNew( state => HandleInvocationResult( null, state as Tuple, long, int, string, ServerResponseContext, RpcErrorMessage> ), tuple ) Link To Source File
msgpack-rpc-cli DispatcherTest.cs Task.Factory.StartNew( () => { } ) Link To Source File
msgpack-rpc-cli TcpServerTransportTest.cs Task.Factory.StartNew( _ => { using ( var buffer = new MemoryStream() ) { using ( var packer = Packer.Create( buffer, false ) ) { PackRequest( packer, id ); } buffer.Position = 0; if ( latch != null ) { latch.Signal(); if ( !latch.Wait( Debugger.IsAttached ? Timeout.Infinite : TimeoutMilliseconds ) ) { throw new TimeoutException(); } } // send buffer.CopyTo( stream ); } }, id ) Link To Source File
msgpack-rpc-cli TcpServerTransportTest.cs Task.Factory.StartNew( _ => { using ( var buffer = new MemoryStream() ) { using ( var packer = Packer.Create( buffer, false ) ) { PackRequest( packer, id ); } buffer.Position = 0; if ( concurrencyLatch != null ) { concurrencyLatch.Signal(); if ( !concurrencyLatch.Wait( Debugger.IsAttached ? Timeout.Infinite : TimeoutMilliseconds ) ) { throw new TimeoutException(); } } // send buffer.CopyTo( stream ); } }, id ) Link To Source File
msgpack-rpc-cli InProcClientTransportManager.cs Task.Factory.StartNew( () => this.GetTransport( null ) as ClientTransport ) Link To Source File
msgpack-rpc-cli CallbackDispatcher.cs Task.Factory.StartNew( () => { MessagePackObject returnValue; try { returnValue = this._callback( messageId, args ); } catch ( Exception exception ) { if ( responseContext != null ) { base.SetException( responseContext, exception ); } else { // notification InvocationHelper.HandleInvocationException( requestContext.SessionId, MessageType.Notification, requestContext.MessageId, requestContext.MethodName, exception, this.IsDebugMode ); } return; } if ( responseContext != null ) { base.SetReturnValue( responseContext, returnValue ); } } ) Link To Source File
KinectRecorder DetphFrameEventData.cs Task.Factory.StartNew(() => { this.imageFrame.Image.saveImage(imgFileDirectory); IO.saveXMLSerialTask(this, tmpEventFileName); }) Link To Source File
KinectRecorder ImageFrameEventData.cs Task.Factory.StartNew(() => { this.imageFrame.Image.saveImage(imgFileDirectory); IO.saveXMLSerialTask(this, tmpEventFileName); }) Link To Source File
KinectRecorder PlanarImage.cs Task.Factory.StartNew(() => { loadImage(eventDataRootFolder); }) Link To Source File
KinectRecorder PlanarImage.cs Task.Factory.StartNew(() => { saveImage(saveRootFolder); }) Link To Source File
KinectRecorder PlanarImage.cs Task.Factory.StartNew(() => { saveByImageDraw(savePath); }) Link To Source File
KinectRecorder PlanarImage.cs Task.Factory.StartNew(() => { saveRawImage(savePath); }) Link To Source File
KinectRecorder SkeletonFrameEventData.cs Task.Factory.StartNew(() => { IO.saveXMLSerialTask(this, tmpEventFileName); }) Link To Source File
KinectRecorder IO.cs Task.Factory.StartNew(() => { saveXMLSerial(obj, fileName); }) Link To Source File
StudyingController UsersStructureViewModel.cs Task.Factory.StartNew(()=> { (CurrentWorkspace.Model as SystemUserModel).Password = PasswordGenerator.Generate(); MailMessage message = new MailMessage(Properties.Resources.EmailOwner,(CurrentWorkspace.Model as SystemUserModel).UserInformation.Email, Properties.Resources.EmailSubject, Properties.Resources.EmailText + (CurrentWorkspace.Model as SystemUserModel).Password); MailSender mail = MailSender.GetInstance(); if(mail.SendMessage(message)) { UserInterop.ShowMessage(String.Format(Properties.Resources.SuccessSendEmail, (CurrentWorkspace.Model as SystemUserModel).Login, (CurrentWorkspace.Model as SystemUserModel).UserInformation.Email)); Dispatcher.Invoke(new Action(()=> (CurrentWorkspace as SaveableViewModel).Save())); } else { UserInterop.ShowMessage(Properties.Resources.ErrorSendEmail); Dispatcher.Invoke(new Action(()=> (CurrentWorkspace as SaveableViewModel).Rollback())); } lock(locker) IsSendingMessage = false; }) Link To Source File