public void LoadMemberReputation(TaskScheduler uiContext) { WebImageRetriever imageDownloader = new WebImageRetriever (); Task<byte[]> loadGraphTask = imageDownloader.GetImageStreamAsync (new Uri (MemberReputationGraphUrl)); loadGraphTask.ContinueWith (t => ReputationGraphLoaded(t.Result), uiContext); }
public CommandsControl() { InitializeComponent(); if (!Program.Running) return; Scheduler = TaskScheduler.FromCurrentSynchronizationContext(); CommandsManager.CommandsController = this; }
private void RunTestLoop(int numberOfTasks, TaskScheduler[] schedulers) { var taskList = new List<Task>(numberOfTasks); for (int i = 0; i < numberOfTasks; i++) { int id = i; // capture Task t = new Task(() => { if (Verbose) output.WriteLine("Task: " + id); }); if (schedulers == null || schedulers.Length == 0) { t.Start(); } else { var scheduler = schedulers[i % schedulers.Length]; t.Start(scheduler); } taskList.Add(t); } Task.WaitAll(taskList.ToArray()); }
/// <summary> /// Uses reflection to set the default scheduler to use for any newly started task. /// </summary> /// <param name="taskScheduler">The <see cref="TaskScheduler"/> to use by default.</param> public static void SetDefaultScheduler(TaskScheduler taskScheduler) { var taskSchedulerType = typeof(TaskScheduler); var defaultTaskSchedulerField = taskSchedulerType.GetField("s_defaultTaskScheduler", BindingFlags.SetField | BindingFlags.Static | BindingFlags.NonPublic); Debug.Assert(defaultTaskSchedulerField != null, "Could not find the TaskScheduler.s_defaultTaskScheduler field. We are assuming this implementation aspect of the .NET Framework to be able to unit test TPL."); defaultTaskSchedulerField.SetValue(null, taskScheduler); }
protected AbstractIndexingExecuter(WorkContext context, IndexReplacer indexReplacer) { this.transactionalStorage = context.TransactionalStorage; this.context = context; this.indexReplacer = indexReplacer; this.scheduler = context.TaskScheduler; }
internal Task RunAsynchronously(TaskScheduler taskScheduler) { Debug.Assert(taskScheduler == TaskScheduler.Default, "PLINQ queries can currently execute only on the default scheduler."); TraceHelpers.TraceInfo("[timing]: {0}: Queue work {1} to occur asynchronously", DateTime.Now.Ticks, _taskIndex); return Task.Factory.StartNew(s_baseWorkDelegate, this, new CancellationToken(), TaskCreationOptions.AttachedToParent | TaskCreationOptions.PreferFairness, taskScheduler); }
/// <summary>Asynchronously iterates through an enumerable of tasks.</summary> /// <param name="factory">The target factory.</param> /// <param name="source">The enumerable containing the tasks to be iterated through.</param> /// <param name="cancellationToken">The cancellation token used to cancel the iteration.</param> /// <param name="creationOptions">Options that control the task's behavior.</param> /// <param name="scheduler">The scheduler to which tasks will be scheduled.</param> /// <returns>A Task that represents the complete asynchronous operation.</returns> public static Task Iterate( this TaskFactory factory, IEnumerable<object> source, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler) { return Iterate(factory, source, null, cancellationToken, creationOptions, scheduler); }
public ViewOrders() { InitializeComponent(); this.scheduler = TaskScheduler.FromCurrentSynchronizationContext(); te = new ThirtyOneEntities(); }
/// <summary> /// Initializes a task notifier watching the specified task. /// </summary> /// <param name="task"> /// The task to watch. /// </param> /// <param name="scheduler"> /// The task scheduler that should be used. /// </param> public NotifyTaskCompletion(Task task, TaskScheduler scheduler) { _task = task; if (task.IsCompleted) { return; } _taskCompleted = task.ContinueWith(t => { NotifyPropertyChanged(() => Status); NotifyPropertyChanged(() => IsCompleted); NotifyPropertyChanged(() => IsNotCompleted); if (t.IsCanceled) { NotifyPropertyChanged(() => IsCanceled); } else if (t.IsFaulted) { NotifyPropertyChanged(() => IsFaulted); NotifyPropertyChanged(() => Exception); NotifyPropertyChanged(() => InnerException); NotifyPropertyChanged(() => ErrorMessage); } else { NotifyPropertyChanged(() => IsSuccessfullyCompleted); } }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, scheduler); }
// This static initialization method *must* be invoked on the UI thread to ensure that the static 'foregroundThread' field is correctly initialized. public static ForegroundThreadAffinitizedObject Initialize(bool force = false) { if (s_foregroundThread != null && !force) { return new ForegroundThreadAffinitizedObject(); } s_foregroundThread = Thread.CurrentThread; var previousContext = SynchronizationContext.Current; try { // None of the work posted to the foregroundTaskScheduler should block pending keyboard/mouse input from the user. // So instead of using the default priority which is above user input, we use Background priority which is 1 level // below user input. SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext(Dispatcher.CurrentDispatcher, DispatcherPriority.Background)); s_foregroundTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext(); } finally { SynchronizationContext.SetSynchronizationContext(previousContext); } return new ForegroundThreadAffinitizedObject(); }
public MockSampleListWorker() { // for GUI synchronized operations mScheduler = TaskScheduler.FromCurrentSynchronizationContext(); // for the remote access example RemotePluginService.StartService(); }
public AntlrBackgroundParser(ITextBuffer textBuffer, TaskScheduler taskScheduler, ITextDocumentFactoryService textDocumentFactoryService, IOutputWindowService outputWindowService) : base(textBuffer, taskScheduler, textDocumentFactoryService, outputWindowService) { Contract.Requires(textBuffer != null); Contract.Requires(taskScheduler != null); Contract.Requires(textDocumentFactoryService != null); Contract.Requires(outputWindowService != null); if (!_initialized) { try { // have to create an instance of the tool to make sure the error manager gets initialized new AntlrTool(); } catch (Exception e) { if (ErrorHandler.IsCriticalException(e)) throw; } _initialized = true; } }
public void Run () { mainScheduler = TaskScheduler.FromCurrentSynchronizationContext (); Task.Run (() => { var url = "http://+:" + port + "/"; var remTries = 2; while (remTries > 0) { remTries--; listener = new HttpListener (); listener.Prefixes.Add (url); try { listener.Start (); remTries = 0; } catch (HttpListenerException ex) { if (remTries == 1 && ex.ErrorCode == 5) { // Access Denied GrantServerPermission (url); } else { throw; } } } Loop (); }); }
public DiffUpdateBackgroundParser(ITextBuffer textBuffer, ITextBuffer documentBuffer, TaskScheduler taskScheduler, ITextDocumentFactoryService textDocumentFactoryService, IGitCommands commands) : base(textBuffer, taskScheduler, textDocumentFactoryService) { _documentBuffer = documentBuffer; _commands = commands; ReparseDelay = TimeSpan.FromMilliseconds(500); if (TextDocumentFactoryService.TryGetTextDocument(_documentBuffer, out _textDocument)) { if (_commands.IsGitRepository(_textDocument.FilePath)) { _textDocument.FileActionOccurred += OnFileActionOccurred; var solutionDirectory = _commands.GetGitRepository(_textDocument.FilePath); if (!string.IsNullOrWhiteSpace(solutionDirectory)) { var gitDirectory = Path.Combine(solutionDirectory, ".git"); _watcher = new FileSystemWatcher(gitDirectory); _watcher.Changed += HandleFileSystemChanged; _watcher.Created += HandleFileSystemChanged; _watcher.Deleted += HandleFileSystemChanged; _watcher.Renamed += HandleFileSystemChanged; _watcher.EnableRaisingEvents = true; } } } }
public ImageProcessor(StateColor setState, ShowState showState, TaskScheduler guiContext, Logger log) { _setState = setState; _showState = showState; GuiContext = guiContext; _logger = log; }
public LogForm(ILogManager logManager) { InitializeComponent(); _logManager = logManager; _uiThread = TaskScheduler.FromCurrentSynchronizationContext(); }
internal QuerySettings Merge(QuerySettings settings2) { if ((this.TaskScheduler != null) && (settings2.TaskScheduler != null)) { throw new InvalidOperationException(System.Linq.SR.GetString("ParallelQuery_DuplicateTaskScheduler")); } if (this.DegreeOfParallelism.HasValue && settings2.DegreeOfParallelism.HasValue) { throw new InvalidOperationException(System.Linq.SR.GetString("ParallelQuery_DuplicateDOP")); } if (this.CancellationState.ExternalCancellationToken.CanBeCanceled && settings2.CancellationState.ExternalCancellationToken.CanBeCanceled) { throw new InvalidOperationException(System.Linq.SR.GetString("ParallelQuery_DuplicateWithCancellation")); } if (this.ExecutionMode.HasValue && settings2.ExecutionMode.HasValue) { throw new InvalidOperationException(System.Linq.SR.GetString("ParallelQuery_DuplicateExecutionMode")); } if (this.MergeOptions.HasValue && settings2.MergeOptions.HasValue) { throw new InvalidOperationException(System.Linq.SR.GetString("ParallelQuery_DuplicateMergeOptions")); } System.Threading.Tasks.TaskScheduler taskScheduler = (this.TaskScheduler == null) ? settings2.TaskScheduler : this.TaskScheduler; int?degreeOfParallelism = this.DegreeOfParallelism.HasValue ? this.DegreeOfParallelism : settings2.DegreeOfParallelism; CancellationToken externalCancellationToken = this.CancellationState.ExternalCancellationToken.CanBeCanceled ? this.CancellationState.ExternalCancellationToken : settings2.CancellationState.ExternalCancellationToken; ParallelExecutionMode?executionMode = this.ExecutionMode.HasValue ? this.ExecutionMode : settings2.ExecutionMode; return(new QuerySettings(taskScheduler, degreeOfParallelism, externalCancellationToken, executionMode, this.MergeOptions.HasValue ? this.MergeOptions : settings2.MergeOptions)); }
/// <summary> /// Initializes a new character instance. /// </summary> /// <param name="p0">Lower left character position.</param> /// <param name="size">Size of the character.</param> /// <param name="uiTaskSchedule">Scheduler associated with the UI thread.</param> public Character(Point p0, Vector size, TaskScheduler uiTaskSchedule) : base(uiTaskSchedule) { this.Position = new Quadrilateral(p0, size); this.Gravity = CharacterGravityState.Down; this.Animation = CharacterAnimationState.Down; }
public PluginController(IUnityContainer container, ErrorHandlingService errorHandlingService) { _container = container; _errorHandlingService = errorHandlingService; _scheduler = TaskScheduler.FromCurrentSynchronizationContext(); LoadedPlugins = new ObservableCollection<Plugin>(); }
internal DiffUpdateBackgroundParser(ITextBuffer textBuffer, ITextBuffer documentBuffer, TaskScheduler taskScheduler, ITextDocumentFactoryService textDocumentFactoryService, IGitCommands commands) : base(textBuffer, taskScheduler, textDocumentFactoryService) { _documentBuffer = documentBuffer; _commands = commands; ReparseDelay = TimeSpan.FromMilliseconds(500); if (TextDocumentFactoryService.TryGetTextDocument(_documentBuffer, out _textDocument)) { if (_commands.IsGitRepository(_textDocument.FilePath)) { _textDocument.FileActionOccurred += OnFileActionOccurred; var repositoryDirectory = _commands.GetGitRepository(_textDocument.FilePath); if (repositoryDirectory != null) { _watcher = new FileSystemWatcher(repositoryDirectory); _watcher.Changed += HandleFileSystemChanged; _watcher.Created += HandleFileSystemChanged; _watcher.Deleted += HandleFileSystemChanged; _watcher.Renamed += HandleFileSystemChanged; _watcher.EnableRaisingEvents = true; } } } }
protected AbstractIndexingExecuter( ITransactionalStorage transactionalStorage, WorkContext context, TaskScheduler scheduler) { this.transactionalStorage = transactionalStorage; this.context = context; this.scheduler = scheduler; }
public void Initialize() { _uiTaskScheduler = TTasks.TaskScheduler.FromCurrentSynchronizationContext(); _taskProvider = new VulnerabilityTaskProvider(this._serviceProvider); _markerProvider = new PackageReferenceMarkerProvider(_taskProvider); _refreshTimer = new Timer(new TimerCallback(RefreshTimer), null, Timeout.Infinite, Timeout.Infinite); _selectionEvents = new EventSinks.VsSelectionEvents(VSPackage.Instance.MonitorSelection); _selectionEvents.SolutionOpened += SelectionEvents_SolutionOpened; _packageInstallerEvents = ServiceLocator.GetInstance <IVsPackageInstallerEvents>(); if (_packageInstallerEvents == null) { throw new InvalidOperationException(string.Format(Resources.Culture, Resources.General_MissingService, typeof(IVsPackageInstallerEvents).FullName)); } _packageInstallerEvents.PackageInstalled += InstallerEvents_PackageInstalled; _packageInstallerEvents.PackageUninstalled += InstallerEvents_PackageUninstalled; _packageInstallerEvents.PackageReferenceAdded += InstallerEvents_PackageReferenceAdded; _packageInstallerEvents.PackageReferenceRemoved += InstallerEvents_PackageReferenceRemoved; _dte = ServiceLocator.GetInstance <DTE>(); if (_dte == null) { throw new InvalidOperationException(string.Format(Resources.Culture, Resources.General_MissingService, typeof(DTE).FullName)); } _documentEvents = _dte.Events.DocumentEvents; _documentEvents.DocumentOpened += OnDocumentOpened; _documentEvents.DocumentClosing += OnDocumentClosing; }
/// <summary> /// Starts a list of tasks. /// </summary> /// <param name="tasks">The tasks to start.</param> /// <param name="exceptions">The variable where to write the occurred exceptions to.</param> /// <param name="scheduler">The custom scheduler to use.</param> /// <returns> /// The started tasks or <see langword="null" /> if <paramref name="tasks" /> is also <see langword="null" />. /// </returns> public static Task[] StartAll( this IEnumerable<Task> tasks, out AggregateException exceptions, TaskScheduler scheduler = null) { exceptions = null; if (tasks == null) { return null; } var occurredExceptions = new List<Exception>(); var startedTasks = new List<Task>(); try { using (var e = tasks.GetEnumerator()) { while (e.MoveNext()) { try { var t = e.Current; if (t == null) { continue; } if (scheduler == null) { t.Start(); } else { t.Start(scheduler); } startedTasks.Add(t); } catch (Exception ex) { occurredExceptions.Add(ex); } } } } catch (Exception ex) { occurredExceptions.Add(ex); } if (occurredExceptions.Count > 0) { exceptions = new AggregateException(occurredExceptions); } return startedTasks.ToArray(); }
public async Task Do(Action act, TaskScheduler scheduler = null) { Exception lastException = null; int retryCount = -1; TimeSpan wait; while (true) { try { var task = new Task(act); task.Start(scheduler); await task.ConfigureAwait(false); break; } catch (OutOfMemoryException) { throw; } catch (Exception ex) { lastException = ex; } retryCount++; if (!GetShouldRetry(retryCount, lastException, out wait)) { ExceptionDispatchInfo.Capture(lastException).Throw(); } else { await Task.Delay(wait).ConfigureAwait(false); } } }
public DatabaseView(string connStr) { InitializeComponent(); this.db = new Database(connStr); currentContext = TaskScheduler.FromCurrentSynchronizationContext(); InitAsync(); }
private void StartRequest(TaskScheduler ui) { HttpWebRequest webRequest = (HttpWebRequest) WebRequest.Create("http://google.ca"); webRequest. BeginGetResponse(asyncResult => { WebResponse response = webRequest.EndGetResponse(asyncResult); Stream stream = response.GetResponseStream(); if (stream == null) return; Task<int> bytesRead = Task<int>.Factory. FromAsync(stream.BeginReadToEnd, stream.EndReadToEnd, inputBuffer, 0, inputBuffer.Length, stream); bytesRead.ContinueWith(ar => { Trace.WriteLine( string.Format("Read {0} bytes", ar.Result)); string text = Encoding.ASCII.GetString( inputBuffer, 0, ar.Result); SetData(text); getHtmlButton.Enabled = true; }, ui); }, webRequest); }
public VirtualUserNetwork(RequestCommand command) { if (command == null) { throw new ArgumentNullException("command"); } if (command.Requests == null || command.Requests.Count == 0) { throw new ArgumentOutOfRangeException("command", Arguments.VirtualUserNetwork_EmptyCommandRequests); } if (command.Users == null) { throw new ArgumentNullException("command.Users"); } if (command.Users.Amount < 1) { throw new ArgumentOutOfRangeException("command.Users.Amount", Arguments.VirtualUserNetwork_AmountNotGreaterThanZero); } ExecutionId = command.ExecutionId; Guid = Guid.NewGuid(); Id = Guid.ToString().Split('-').First().ToUpper(); userSettings = command.Users; taskScheduler = new WorkStealingTaskScheduler(userSettings.Amount); tokenSource = new CancellationTokenSource(); queue = new ConcurrentQueue<IRestRequest>(command.Requests); users = new ConcurrentBag<VirtualUser>(); RestClient = command.Client; SleepTime = command.Users.SleepTime; }
public WorldViewModel() { _uiScheduler = TaskScheduler.FromCurrentSynchronizationContext(); _uiFactory = new TaskFactory(_uiScheduler); Tools = new OrderingCollection<ITool, IOrderMetadata>(t => t.Metadata.Order); CompositionTarget.Rendering += CompTargetRender; }
/// <summary> /// Creates a new source monitor /// </summary> /// <param name="solution">The solution to monitor</param> /// <param name="foldersToMonitor">A list of folders to monitor</param> /// <param name="scanInterval">The interval at which to scan the folders (in /// seconds) </param> /// <param name="baseDirectory">The base directory for this monitor</param> /// <param name="defaultArchive">The default archive to route files to</param> /// <param name="otherArchives">Other archives to route files to</param> public SourceMonitor(Solution solution, double scanInterval, TaskScheduler scheduler, string baseDirectory, AbstractArchive defaultArchive, SrcMLArchive sourceArchive, params AbstractArchive[] otherArchives) : base(DirectoryScanningMonitor.MONITOR_LIST_FILENAME, scanInterval, scheduler, baseDirectory, defaultArchive, otherArchives) { if(null != sourceArchive) { RegisterArchive(sourceArchive, false); } this.MonitoredSolution = solution; }
public YoutubePlayerControl() { InitializeComponent(); if (!Program.Running) return; Scheduler = TaskScheduler.FromCurrentSynchronizationContext(); }
/// <summary> /// Creates a new project object /// </summary> /// <param name="scheduler">The task scheduler</param> /// <param name="monitor">The file monitor</param> ///<param name="generator">The SrcML generator to use</param> public SrcMLProject(TaskScheduler scheduler, AbstractFileMonitor monitor, SrcMLGenerator generator) { Scheduler = scheduler; Monitor = monitor; SetupMonitor(generator); SourceArchive.Generator.IsLoggingErrors = true; SourceArchive.Generator.ErrorLog = new StreamWriter(Path.Combine(StoragePath, "error.log"), false); }
public DeadPeerDetectorEntry(PeerDescriptor descriptor, IDirectoryConfiguration configuration, IBus bus, TaskScheduler taskScheduler) { Descriptor = descriptor; _configuration = configuration; _bus = bus; _taskScheduler = taskScheduler; }
internal QuerySettings(System.Threading.Tasks.TaskScheduler taskScheduler, int?degreeOfParallelism, CancellationToken externalCancellationToken, ParallelExecutionMode?executionMode, ParallelMergeOptions?mergeOptions) { this.m_taskScheduler = taskScheduler; this.m_degreeOfParallelism = degreeOfParallelism; this.m_cancellationState = new System.Linq.Parallel.CancellationState(externalCancellationToken); this.m_executionMode = executionMode; this.m_mergeOptions = mergeOptions; this.m_queryId = -1; }
private void Form1_Load(object sender, EventArgs e) { taskScheduler = System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext(); System.Threading.Tasks.Task.Factory.StartNew(() => { while (true) { label1.Text = DateTime.Now.ToLongTimeString(); } }); }
public BackgroundWorkerServer(IBackgroundWorker worker, Scheduler scheduler) { if (worker == null) { throw new ArgumentNullException(nameof(worker)); } if (scheduler == null) { throw new ArgumentNullException(nameof(scheduler)); } _worker = worker; _scheduler = scheduler; }
/// <summary> /// Creates and starts a task. /// </summary> public static SystemTask StartNew(SystemTaskFactory factory, Action action, SystemCancellationToken cancellationToken, SystemTaskCreationOptions creationOptions, SystemTaskScheduler scheduler) { var runtime = CoyoteRuntime.Current; if (runtime.SchedulingPolicy is SchedulingPolicy.None || scheduler.GetType() != SystemTaskScheduler.Default.GetType()) { return(factory.StartNew(action, cancellationToken, creationOptions, scheduler)); } return(runtime.TaskFactory.StartNew(action, cancellationToken, runtime.TaskFactory.CreationOptions | creationOptions, runtime.TaskFactory.Scheduler)); }
/// <summary> /// Constructor for the Application object. /// </summary> public App() { System.Threading.SynchronizationContext sc = new System.Threading.SynchronizationContext(); UITaskScheduler = TaskScheduler.FromCurrentSynchronizationContext(); // Global handler for uncaught exceptions. UnhandledException += Application_UnhandledException; // Standard XAML initialization InitializeComponent(); // Phone-specific initialization InitializePhoneApplication(); // Language display initialization InitializeLanguage(); // Show graphics profiling information while debugging. if (Debugger.IsAttached) { // Display the current frame rate counters. Application.Current.Host.Settings.EnableFrameRateCounter = true; // Show the areas of the app that are being redrawn in each frame. //Application.Current.Host.Settings.EnableRedrawRegions = true; // Enable non-production analysis visualization mode, // which shows areas of a page that are handed off to GPU with a colored overlay. //Application.Current.Host.Settings.EnableCacheVisualization = true; // Prevent the screen from turning off while under the debugger by disabling // the application's idle detection. // Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run // and consume battery power when the user is not using the phone. PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled; } }
/// <summary>Initializes a new continuation.</summary> /// <param name="task">The task to be activated.</param> /// <param name="options">The continuation options.</param> /// <param name="scheduler">The scheduler to use for the continuation.</param> internal StandardTaskContinuation(Task task, TaskContinuationOptions options, TaskScheduler scheduler) { Debug.Assert(task != null, "TaskContinuation ctor: task is null"); Debug.Assert(scheduler != null, "TaskContinuation ctor: scheduler is null"); m_task = task; m_options = options; m_taskScheduler = scheduler; if (AsyncCausalityTracer.LoggingOn) { AsyncCausalityTracer.TraceOperationCreation(m_task, "Task.ContinueWith: " + task.m_action !.Method.Name); } if (Task.s_asyncDebuggingEnabled) { Task.AddToActiveTasks(m_task); } }
public TaskSchedulerDebuggerView(TaskScheduler scheduler) { this.scheduler = scheduler; }
internal Task(Action <object> action, object state, Task parent, CancellationToken cancellationToken, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler) : this((Delegate)action, state, parent, cancellationToken, creationOptions, internalOptions, scheduler) { CapturedContext = ExecutionContext.Capture(); }
internal bool TryStart(TaskScheduler scheduler, bool inline) { return(Volatile.Read(ref _isDisposed) != 1 && InternalStart(scheduler, inline, true)); }
/// <summary> /// Initializes the AsyncCall with a function to execute for each element. The function returns an Task /// that represents the asynchronous completion of that element's processing. /// </summary> /// <param name="functionHandler">The function to run for every posted item.</param> /// <param name="maxDegreeOfParallelism">The maximum degree of parallelism to use. If not specified, 1 is used for serial execution.</param> /// <param name="scheduler">The scheduler to use. If null, the default scheduler is used.</param> public AsyncCall(Func <T, Task> functionHandler, int maxDegreeOfParallelism = 1, TaskScheduler scheduler = null) : this(maxDegreeOfParallelism, 1, scheduler) => _handler = functionHandler ?? throw new ArgumentNullException("handler");
public Task <TNewResult> ContinueWith <TNewResult>(Func <Task <TResult>, object, TNewResult> continuationFunction, object state, TaskScheduler scheduler) { return(ContinueWith <TNewResult>(continuationFunction, state, CancellationToken.None, TaskContinuationOptions.None, scheduler)); }
/// <summary>Executes a for each operation on an <see cref="System.Collections.Generic.IEnumerable{TSource}"/> in which iterations may run in parallel.</summary> /// <typeparam name="TSource">The type of the data in the source.</typeparam> /// <param name="source">An enumerable data source.</param> /// <param name="dop">A integer indicating how many operations to allow to run in parallel.</param> /// <param name="scheduler">The task scheduler on which all code should execute.</param> /// <param name="cancellationToken">A cancellation token that may be used to cancel the for each operation.</param> /// <param name="body">An asynchronous delegate that is invoked once per element in the data source.</param> /// <exception cref="System.ArgumentNullException">The exception that is thrown when the <paramref name="source"/> argument or <paramref name="body"/> argument is null.</exception> /// <returns>A task that represents the entire for each operation.</returns> private static Task ForEachAsync <TSource>(IEnumerable <TSource> source, int dop, TaskScheduler scheduler, CancellationToken cancellationToken, Func <TSource, CancellationToken, ValueTask> body) { Debug.Assert(source != null); Debug.Assert(scheduler != null); Debug.Assert(body != null); // One fast up-front check for cancellation before we start the whole operation. if (cancellationToken.IsCancellationRequested) { return(Task.FromCanceled(cancellationToken)); } if (dop < 0) { dop = DefaultDegreeOfParallelism; } // The worker body. Each worker will execute this same body. Func <object, Task> taskBody = static async o =>
/// <summary> /// Initializes the <see cref="AsyncCall{T}"/> with a function to execute for each element. The function returns a <see cref="Task"/> /// that represents the asynchronous completion of that element's processing. /// </summary> /// <param name="functionHandler">The function to run for every posted item.</param> /// <param name="maxDegreeOfParallelism">The maximum degree of parallelism to use. If not specified, 1 is used for serial execution.</param> /// <param name="scheduler">The scheduler to use. If <see langword="null"/>, the default scheduler is used.</param> public AsyncCall(Func <T, Task> functionHandler, int maxDegreeOfParallelism = 1, TaskScheduler scheduler = null) : this(maxDegreeOfParallelism, 1, scheduler) { if (functionHandler == null) { throw new ArgumentNullException(nameof(functionHandler)); } _handler = functionHandler; }
/// <summary>Initializes a new continuation.</summary> /// <param name="task">The task to be activated.</param> /// <param name="options">The continuation options.</param> /// <param name="scheduler">The scheduler to use for the continuation.</param> internal StandardTaskContinuation(Task task, TaskContinuationOptions options, TaskScheduler scheduler) { Contract.Requires(task != null, "TaskContinuation ctor: task is null"); Contract.Requires(scheduler != null, "TaskContinuation ctor: scheduler is null"); m_task = task; m_options = options; m_taskScheduler = scheduler; if (AsyncCausalityTracer.LoggingOn) { AsyncCausalityTracer.TraceOperationCreation(CausalityTraceLevel.Required, m_task.Id, "Task.ContinueWith: " + ((Delegate)task.m_action).Method.Name, 0); } if (Task.s_asyncDebuggingEnabled) { Task.AddToActiveTasks(m_task); } }
public SystemThreadingTasks_TaskSchedulerDebugView(TaskScheduler scheduler) { m_taskScheduler = scheduler; }
private TaskReplicator(ParallelOptions options, bool stopOnFirstFailure) { _scheduler = options.TaskScheduler ?? TaskScheduler.Current; _stopOnFirstFailure = stopOnFirstFailure; }
/// <summary> /// TaskSchedulerからTaskを呼び出し。 /// </summary> /// <param name="scheduler"></param> /// <param name="action"></param> /// <returns></returns> public static System.Threading.Tasks.Task TaskStart(this System.Threading.Tasks.TaskScheduler scheduler, Action action) { return(System.Threading.Tasks.Task.Factory.StartNew(action, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, scheduler)); }
void InitDataFlow() { //Create schedulers scheduler = new QueuedTaskScheduler(System.Threading.Tasks.TaskScheduler.Default, PARALLEL_READS); highPriorityScheduler = scheduler.ActivateNewQueue(0); lowPriorityScheduler = scheduler.ActivateNewQueue(1); //create options optionsReadHighP = new ExecutionDataflowBlockOptions { TaskScheduler = highPriorityScheduler, MaxDegreeOfParallelism = PARALLEL_READS, CancellationToken = cancelTokenSrc.Token }; //create options optionsReadHighP = new ExecutionDataflowBlockOptions { TaskScheduler = highPriorityScheduler, MaxDegreeOfParallelism = PARALLEL_READS, CancellationToken = cancelTokenSrc.Token }; optionsReadLowP = new ExecutionDataflowBlockOptions { TaskScheduler = lowPriorityScheduler, MaxDegreeOfParallelism = PARALLEL_READS, CancellationToken = cancelTokenSrc.Token }; optionsWriteBlock = new ExecutionDataflowBlockOptions { CancellationToken = cancelTokenSrc.Token }; optionsBatchBlock = new GroupingDataflowBlockOptions { Greedy = true, CancellationToken = cancelTokenSrc.Token, }; optionsLink = new DataflowLinkOptions { PropagateCompletion = true, }; // CollectionInfoSaver collectionInfoSaver = new CollectionInfoSaver(logger); //create blocks bufferBlockHighP = new BufferBlock <SchedulerJob>(); bufferBlockLowP = new BufferBlock <SchedulerJob>(); highPriorityReadInfoBlock = new TransformBlock <SchedulerJob, CollectionResult>(async(sqlJob) => { if (sqlJob != null) { if (sqlJob.JobUpdater != null) { return(await sqlJob.JobUpdater.UpdateJob(sqlJob)); } } return(null); }, optionsReadHighP); lowPriorityReadInfoBlock = new TransformBlock <SchedulerJob, CollectionResult>(async(sqlJob) => { if (sqlJob != null) { if (sqlJob.JobUpdater != null) { return(await sqlJob.JobUpdater.UpdateJob(sqlJob)); } } return(null); }, optionsReadLowP); batchBlock = new BatchBlock <CollectionResult>(1, optionsBatchBlock); writeInfoBlock = new ActionBlock <CollectionResult[]>(sqlInfoArray => ResultSaver.SaveResults(sqlInfoArray), optionsWriteBlock); //link blocks bufferBlockHighP.LinkTo(highPriorityReadInfoBlock, optionsLink); bufferBlockLowP.LinkTo(lowPriorityReadInfoBlock, optionsLink); highPriorityReadInfoBlock.LinkTo(batchBlock, optionsLink); lowPriorityReadInfoBlock.LinkTo(batchBlock, optionsLink); batchBlock.LinkTo(writeInfoBlock, optionsLink); }
/// <summary> /// Initializes the ConcurrentExclusiveSchedulerPair to target the specified scheduler with a maximum concurrency level. /// </summary> /// <param name="taskScheduler">The target scheduler on which this pair should execute.</param> /// <param name="maxConcurrencyLevel">The maximum number of tasks to run concurrently.</param> public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler, int maxConcurrencyLevel) : this(taskScheduler, maxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK) { }
internal static int GetBestWorkerNumber(TaskScheduler scheduler) { return(Math.Min(Environment.ProcessorCount, (scheduler ?? TaskScheduler.Current).MaximumConcurrencyLevel)); }
/// <summary>General initialization of the <see cref="AsyncCall{T}"/>. Another constructor must initialize the delegate.</summary> /// <param name="maxDegreeOfParallelism">The maximum degree of parallelism to use. If not specified, 1 is used for serial execution.</param> /// <param name="maxItemsPerTask">The maximum number of items to be processed per task. If not specified, <see cref="int.MaxValue"/> is used.</param> /// <param name="scheduler">The scheduler to use. If <see langword="null"/>, the default scheduler is used.</param> private AsyncCall(int maxDegreeOfParallelism = 1, int maxItemsPerTask = Int32.MaxValue, TaskScheduler scheduler = null) { // Validate arguments if (maxDegreeOfParallelism < 1) { throw new ArgumentOutOfRangeException(nameof(maxDegreeOfParallelism)); } if (maxItemsPerTask < 1) { throw new ArgumentOutOfRangeException(nameof(maxItemsPerTask)); } if (scheduler == null) { scheduler = TaskScheduler.Default; } // Configure the instance _queue = new ConcurrentQueue <T>(); _maxItemsPerTask = maxItemsPerTask; _tf = new TaskFactory(scheduler); if (maxDegreeOfParallelism != 1) { _parallelOptions = new ParallelOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism, TaskScheduler = scheduler }; } }
/// <summary> /// An internal constructor used by the factory methods on task and its descendent(s). /// This variant does not capture the ExecutionContext; it is up to the caller to do that. /// </summary> /// <param name="action">An action to execute.</param> /// <param name="state">Optional state to pass to the action.</param> /// <param name="parent">Parent of Task.</param> /// <param name="cancellationToken">A CancellationToken for the task.</param> /// <param name="creationOptions">Options to control its execution.</param> /// <param name="internalOptions">Internal options to control its execution</param> /// <param name="scheduler">A task scheduler under which the task will run.</param> internal Task(Delegate action, object state, Task parent, CancellationToken cancellationToken, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler) { #pragma warning disable IDE0016 // Usar expresión "throw" if (action == null) { throw new ArgumentNullException(nameof(action)); } if (scheduler == null) { throw new ArgumentNullException(nameof(scheduler)); } #pragma warning restore IDE0016 // Usar expresión "throw" Contract.EndContractBlock(); // This is readonly, and so must be set in the constructor // Keep a link to your parent if: (A) You are attached, or (B) you are self-replicating. if ( (creationOptions & TaskCreationOptions.AttachedToParent) != 0 || (internalOptions & InternalTaskOptions.SelfReplicating) != 0 ) { _parent = parent; } Id = Interlocked.Increment(ref _lastId) - 1; _status = (int)TaskStatus.Created; if ( _parent != null && (creationOptions & TaskCreationOptions.AttachedToParent) != 0 && (_parent.CreationOptions & TaskCreationOptions.DenyChildAttach) == 0 ) { _parent.AddNewChild(); } ExecutingTaskScheduler = scheduler; Action = action; State = state; _waitHandle = new ManualResetEventSlim(false); if ((creationOptions & ~(TaskCreationOptions.AttachedToParent | TaskCreationOptions.LongRunning | TaskCreationOptions.DenyChildAttach | TaskCreationOptions.HideScheduler | TaskCreationOptions.PreferFairness | TaskCreationOptions.RunContinuationsAsynchronously)) != 0) { throw new ArgumentOutOfRangeException(nameof(creationOptions)); } // Throw exception if the user specifies both LongRunning and SelfReplicating if ((creationOptions & TaskCreationOptions.LongRunning) != 0 && (internalOptions & InternalTaskOptions.SelfReplicating) != 0) { throw new InvalidOperationException("An attempt was made to create a LongRunning SelfReplicating task."); } if ((internalOptions & InternalTaskOptions.ContinuationTask) != 0) { // For continuation tasks or TaskCompletionSource.Tasks, begin life in the // WaitingForActivation state rather than the Created state. _status = (int)TaskStatus.WaitingForActivation; } CreationOptions = creationOptions; _internalOptions = internalOptions; // if we have a non-null cancellationToken, allocate the contingent properties to save it // we need to do this as the very last thing in the construction path, because the CT registration could modify m_stateFlags if (cancellationToken.CanBeCanceled) { AssignCancellationToken(cancellationToken, null, null); } }
/// <summary>Initializes the <see cref="AsyncCall{T}"/> with an action to execute for each element.</summary> /// <param name="actionHandler">The action to run for every posted item.</param> /// <param name="maxDegreeOfParallelism">The maximum degree of parallelism to use. If not specified, 1 is used for serial execution.</param> /// <param name="scheduler">The scheduler to use. If <see langword="null"/>, the default scheduler is used.</param> /// <param name="maxItemsPerTask">The maximum number of items to be processed per task. If not specified, <see cref="int.MaxValue"/> is used.</param> public AsyncCall(Action <T> actionHandler, int maxDegreeOfParallelism = 1, int maxItemsPerTask = Int32.MaxValue, TaskScheduler scheduler = null) : this(maxDegreeOfParallelism, maxItemsPerTask, scheduler) { if (actionHandler == null) { throw new ArgumentNullException(nameof(actionHandler)); } _handler = actionHandler; }
internal Task(Action action, Task parent, CancellationToken cancellationToken, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler) : this(action, null, parent, cancellationToken, creationOptions, internalOptions, scheduler) { CapturedContext = ExecutionContext.Capture(); }
/// <summary>Initializes the AsyncCall with an action to execute for each element.</summary> /// <param name="actionHandler">The action to run for every posted item.</param> /// <param name="maxDegreeOfParallelism">The maximum degree of parallelism to use. If not specified, 1 is used for serial execution.</param> /// <param name="scheduler">The scheduler to use. If null, the default scheduler is used.</param> /// <param name="maxItemsPerTask">The maximum number of items to be processed per task. If not specified, Int32.MaxValue is used.</param> public AsyncCall(Action <T> actionHandler, int maxDegreeOfParallelism = 1, int maxItemsPerTask = int.MaxValue, TaskScheduler scheduler = null) : this(maxDegreeOfParallelism, maxItemsPerTask, scheduler) => _handler = actionHandler ?? throw new ArgumentNullException("handler");
/// <summary>Asynchronously iterates through an enumerable of tasks.</summary> /// <param name="factory">The target factory.</param> /// <param name="source">The enumerable containing the tasks to be iterated through.</param> /// <param name="cancellationToken">The cancellation token used to cancel the iteration.</param> /// <param name="creationOptions">Options that control the task's behavior.</param> /// <param name="scheduler">The scheduler to which tasks will be scheduled.</param> /// <returns>A <see cref="Task"/> that represents the complete asynchronous operation.</returns> public static Task Iterate( this TaskFactory factory, IEnumerable <object> source, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler) { return(Iterate(factory, source, null, cancellationToken, creationOptions, scheduler)); }
/// <summary> /// Creates and starts a task. /// </summary> public static SystemTasks.Task <TResult> StartNew <TResult>(SystemTaskFactory factory, Func <object, TResult> function, object state, SystemCancellationToken cancellationToken, SystemTaskCreationOptions creationOptions, SystemTaskScheduler scheduler) { var runtime = CoyoteRuntime.Current; if (runtime.SchedulingPolicy is SchedulingPolicy.None || scheduler.GetType() != SystemTaskScheduler.Default.GetType()) { return(factory.StartNew(function, state, cancellationToken, creationOptions, scheduler)); } return(runtime.TaskFactory.StartNew(function, state, cancellationToken, runtime.TaskFactory.CreationOptions | creationOptions, runtime.TaskFactory.Scheduler)); }
/// <summary>Asynchronously iterates through an enumerable of tasks.</summary> /// <param name="factory">The target factory.</param> /// <param name="source">The enumerable containing the tasks to be iterated through.</param> /// <param name="state">The asynchronous state for the returned <see cref="Task"/>.</param> /// <param name="cancellationToken">The cancellation token used to cancel the iteration.</param> /// <param name="creationOptions">Options that control the task's behavior.</param> /// <param name="scheduler">The scheduler to which tasks will be scheduled.</param> /// <returns>A <see cref="Task"/> that represents the complete asynchronous operation.</returns> public static Task Iterate( this TaskFactory factory, IEnumerable <object> source, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler) { // Validate/update parameters if (factory == null) { throw new ArgumentNullException(nameof(factory)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } if (scheduler == null) { throw new ArgumentNullException(nameof(scheduler)); } // Get an enumerator from the enumerable var enumerator = source.GetEnumerator(); if (enumerator == null) { throw new InvalidOperationException("Invalid enumerable - GetEnumerator returned null"); } // Create the task to be returned to the caller. And ensure // that when everything is done, the enumerator is cleaned up. var trs = new TaskCompletionSource <object>(state, creationOptions); trs.Task.ContinueWith(_ => enumerator.Dispose(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); // This will be called every time more work can be done. Action <Task> recursiveBody = null; recursiveBody = antecedent => { try { // If we should continue iterating and there's more to iterate // over, create a continuation to continue processing. We only // want to continue processing once the current Task (as yielded // from the enumerator) is complete. if (enumerator.MoveNext()) { var nextItem = enumerator.Current; // If we got a Task, continue from it to continue iterating if (nextItem is Task) { var nextTask = (Task)nextItem; /**/ nextTask.IgnoreExceptions(); // TODO: Is this a good idea? nextTask.ContinueWith(recursiveBody).IgnoreExceptions(); } // If we got a scheduler, continue iterating under the new scheduler, // enabling hopping between contexts. else if (nextItem is TaskScheduler) { Task.Factory.StartNew(() => recursiveBody(null), CancellationToken.None, TaskCreationOptions.None, (TaskScheduler)nextItem).IgnoreExceptions(); } // Anything else is invalid else { trs.TrySetException(new InvalidOperationException("Task or TaskScheduler object expected in Iterate")); } } // Otherwise, we're done! else { trs.TrySetResult(null); } } // If MoveNext throws an exception, propagate that to the user, // either as cancellation or as a fault catch (Exception exc) { var oce = exc as OperationCanceledException; if (oce != null && oce.CancellationToken == cancellationToken) { trs.TrySetCanceled(); } else { trs.TrySetException(exc); } } }; // Get things started by launching the first task factory.StartNew(() => recursiveBody(null), CancellationToken.None, TaskCreationOptions.None, scheduler).IgnoreExceptions(); // Return the representative task to the user return(trs.Task); }