public VectorStrokeHandler(Renderer renderer, VectorBrushStyle style, MediaColor color) : base(renderer, color) { BrushColor = color; SetBrushStyle(style); // Spatial Model mSpatialModel = new SpatialModel(new VectorInkStrokeFactory()); mSpatialModel.StrokeAdded += OnSpatialModelStrokeAdded; mSpatialModel.StrokeRemoved += OnSpatialModelStrokeRemoved; mSpatialModel.StrokeSelected += OnSpatialModelStrokeSelected; mSpatialModel.EraseFinished += OnSpatialModelEraseFinished; mSpatialModel.SelectStarted += OnSpatialModelSelectStarted; mSpatialModel.SelectFinished += OnSpatialModelSelectFinished; WorkItemHandler workItemHandler = new WorkItemHandler((IAsyncAction action) => { try { mSpatialModel.StartProcessingJobs(); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine($"Exception: {ex.Message}"); } }); mSpatialModelLoopWorker = Windows.System.Threading.ThreadPool.RunAsync(workItemHandler, WorkItemPriority.High, WorkItemOptions.TimeSliced); }
public void Start() { Debug.LogMessage("WorkManager.Start"); // make sure events are processed before entering main loop, because the window may not be visible yet. CoreWindow.GetForCurrentThread().Dispatcher.ProcessEvents(CoreProcessEventsOption.ProcessAllIfPresent); IAsyncAction mainLoopWorker; WorkItemHandler workHandler = new WorkItemHandler((IAsyncAction action) => { Debug.LogMessage("WorkManager *** thread started *** "); while ((action.Status == AsyncStatus.Started) && State != WorkManagerStates.Exiting) { if (State == WorkManagerStates.Running) { } } // signal application quit or else ProcessUntilQuit will wait for windows close button press coreApp.Exit(); Debug.LogMessage("WorkManager *** thread terminated ***"); }); mainLoopWorker = ThreadPool.RunAsync(workHandler, WorkItemPriority.High, WorkItemOptions.TimeSliced); // ProcessUntilQuit will block the UI thread and process events as they appear until the App terminates. CoreWindow.GetForCurrentThread().Dispatcher.ProcessEvents(CoreProcessEventsOption.ProcessUntilQuit); }
public InputEvents(CoreWindow window, UIElement inputElement, TouchQueue touchQueue) { _touchQueue = touchQueue; // The key events are always tied to the window as those will // only arrive here if some other control hasn't gotten it. window.KeyDown += CoreWindow_KeyDown; window.KeyUp += CoreWindow_KeyUp; window.VisibilityChanged += CoreWindow_VisibilityChanged; window.Activated += CoreWindow_Activated; window.SizeChanged += CoreWindow_SizeChanged; DisplayInformation.GetForCurrentView().DpiChanged += InputEvents_DpiChanged; _currentDipFactor = DisplayInformation.GetForCurrentView().LogicalDpi / 96.0f; if (inputElement is SwapChainPanel || inputElement is SwapChainBackgroundPanel) { // Create a thread to precess input events. var workItemHandler = new WorkItemHandler((action) => { var inputDevices = CoreInputDeviceTypes.Mouse | CoreInputDeviceTypes.Pen | CoreInputDeviceTypes.Touch; CoreIndependentInputSource coreIndependentInputSource; if (inputElement is SwapChainBackgroundPanel) { coreIndependentInputSource = ((SwapChainBackgroundPanel)inputElement).CreateCoreIndependentInputSource(inputDevices); } else { coreIndependentInputSource = ((SwapChainPanel)inputElement).CreateCoreIndependentInputSource(inputDevices); } coreIndependentInputSource.PointerPressed += CoreWindow_PointerPressed; coreIndependentInputSource.PointerMoved += CoreWindow_PointerMoved; coreIndependentInputSource.PointerReleased += CoreWindow_PointerReleased; coreIndependentInputSource.Dispatcher.ProcessEvents(CoreProcessEventsOption.ProcessUntilQuit); }); var inputWorker = ThreadPool.RunAsync(workItemHandler, WorkItemPriority.High, WorkItemOptions.TimeSliced); } if (inputElement != null) { // If we have an input UIElement then we bind input events // to it else we'll get events for overlapping XAML controls. inputElement.PointerPressed += UIElement_PointerPressed; inputElement.PointerReleased += UIElement_PointerReleased; inputElement.PointerCanceled += UIElement_PointerReleased; inputElement.PointerMoved += UIElement_PointerMoved; inputElement.PointerWheelChanged += UIElement_PointerWheelChanged; } else { // If we only have a CoreWindow then use it for input events. window.PointerPressed += CoreWindow_PointerPressed; window.PointerReleased += CoreWindow_PointerReleased; window.PointerMoved += CoreWindow_PointerMoved; window.PointerWheelChanged += CoreWindow_PointerWheelChanged; } }
public async Task StartSearch(ObservableCollection <GroupingAttribute> compareAttribsList) { _tokenSource = new CancellationTokenSource(); CancellationToken token = _tokenSource.Token; WorkItemHandler workhandler = delegate { Search(compareAttribsList, token); }; await ThreadPool.RunAsync(workhandler, WorkItemPriority.High, WorkItemOptions.TimeSliced); }
/// <summary> /// Checks if a task is due, and starts it. /// </summary> /// <param name="state">The current <see cref="Scheduler{T}"/>.</param> private void TriggerCallback(object state) { if (IsDisposed || !mIsEnabled) { return; } lock (SyncRoot) { foreach (ScheduledTask <T> task in mTasks) { if (!mIsEnabled) { break; } if (task.IsTaskDue && !ScheduledTasks.ContainsKey(task)) { WorkItemHandler wih = new WorkItemHandler((IAsyncAction operation) => { AsyncActionSchedulerAction sa = new AsyncActionSchedulerAction(operation); try { if (sa.IsCancellationRequested || OnTaskStarting(task)) { sa.IsCanceled = true; } else { task.Run(sa); } } catch (OperationCanceledException ex) { sa.IsSuccess = false; sa.IsCanceled = true; sa.Exception = ex; } catch (Exception ex) { sa.IsSuccess = false; sa.IsCanceled = false; sa.Exception = ex; } finally { OnTaskCompleted(task, sa); SpinWait.SpinUntil(() => { return(ScheduledTasks.Remove(task)); }, 100); task.UpdateSchedule(DateTimeOffset.Now); task.IsScheduled = false; sa.Operation.Close(); } }); task.IsScheduled = true; ScheduledTasks.Add(task, ThreadPool.RunAsync(wih, WorkItemPriority.Normal, WorkItemOptions.TimeSliced)); } } } }
/// <summary> /// Перегруппировывает результаты поиска дубликатов по заданному атрибуту /// </summary> /// <param name="attribute"></param> public async void RegroupResultsByFileAttribute(GroupingAttribute attribute) { _tokenSource = new CancellationTokenSource(); CancellationToken token = _tokenSource.Token; WorkItemHandler workhandler = delegate { Regroup(attribute, token); }; await ThreadPool.RunAsync(workhandler, WorkItemPriority.High, WorkItemOptions.TimeSliced); _duplicatesCollection.Invalidate(); }
protected override Task OnChangeRoleAsync(ReplicaRole newRole, CancellationToken cancellationToken) { if (newRole != ReplicaRole.Primary) { BackupRestoreTrace.TraceSource.WriteInfo(TraceType, "Stoping the WorkItem Handler"); WorkItemHandler.StopWorkItemHandler(); BackupRestoreTrace.TraceSource.WriteInfo(TraceType, "Stopped the WorkItem Handler"); } return(base.OnChangeRoleAsync(newRole, cancellationToken)); }
public override void StartRunLoop() { var workItemHandler = new WorkItemHandler((action) => { while (true) { MetroGameWindow.Instance.Tick(); } }); var tickWorker = ThreadPool.RunAsync(workItemHandler, WorkItemPriority.High, WorkItemOptions.TimeSliced); }
/// <summary> /// Instantiates a new WorkThread given the WorkItemHandler. /// </summary> /// <param name="workQueue">The queue containing workitems.</param> /// <param name="workItemHandler">Handler that will handle WorkItems.</param> public WorkThread(SynchronisedQueue <T> workQueue, WorkItemHandler <T> workItemHandler) { // Initialize: this.workQueue = workQueue; this.workItemHandler = workItemHandler; // Start workthread: this.workThread = new Thread(this.HandleQueue); this.workThread.Name = Guid.NewGuid().ToString(); this.workThread.IsBackground = true; this.workThread.Start(); }
public static IAsyncAction RunAsync (WorkItemHandler handler) { if (handler == null) throw new ArgumentException ("handler"); var action = new TaskAction (a => { try { handler ((IAsyncAction)a); } catch { } }); action.AsyncState = action; return action; }
/// <summary> /// Steps a specified number of steps, direction and stepping style. /// </summary> /// <param name="steps">The number of steps to process.</param> /// <param name="direction">A <see cref="Direction"/>.</param> /// <param name="stepStyle">A <see cref="SteppingStyle"/>.</param> /// <remarks> /// StepAsync cannot be called if the motor is already running. /// </remarks> public IAsyncAction StepAsync(int steps, Direction direction, SteppingStyle stepStyle) { if (_stepAsyncState == MotorState.Run) { throw new InvalidOperationException("Stepper motor is already running."); } cts = new CancellationTokenSource(); _stepStyle = stepStyle; WorkItemHandler loop = new WorkItemHandler((IAsyncAction) => motorThread(steps, direction, stepStyle, cts.Token) ); _runTask = ThreadPool.RunAsync(loop, WorkItemPriority.High); return(_runTask); }
/// <summary> /// This is the main entry point for your service replica. /// This method executes when this replica of your service becomes primary and has write status. /// </summary> /// <param name="cancellationToken">Canceled when Service Fabric needs to shut down this service replica.</param> protected override async Task RunAsync(CancellationToken cancellationToken) { BackupRestoreTrace.TraceSource.WriteInfo(TraceType, "Enter RunAsync"); FabricEvents.Events.BackupRestoreEnabled(this.Context.TraceId); // TODO: Ensure that the requests dont come in before we do the necessary initializations which are being done below await WorkItemHandler.StartAndScheduleWorkItemHandler(this); BackupRestoreTrace.TraceSource.WriteInfo(TraceType, "Registering config update handlers now"); var configUpdateHandler = new ConfigUpdateHandler(); configStore = NativeConfigStore.FabricGetConfigStore(configUpdateHandler); var certConfigHandler = new EncryptionCertConfigHandler(this.EncryptionCertUpdateCallbackAsync, this, cancellationToken); encryptionCertConfigStore = NativeConfigStore.FabricGetConfigStore(certConfigHandler); await certConfigHandler.InitializeAsync(); Task <RetentionManager> retentionManagerTask = RetentionManager.CreateOrGetRetentionManager(this); BackupRestoreTrace.TraceSource.WriteInfo(TraceType, "Config update handlers registered"); try { while (!configUpdateHandler.ProcessRecycleRequired) { cancellationToken.ThrowIfCancellationRequested(); if (this.retentionManager == null && retentionManagerTask.IsCompleted) { this.retentionManager = retentionManagerTask.Result; } await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken); } // Process recycle is required, throwing exception from RunAsync throw new Exception("Process recycle needed."); } finally { this.retentionManager?.StopRetentionManager(); BackupRestoreTrace.TraceSource.WriteInfo(TraceType, "Exit RunAsync"); } }
public StopVideoControl() { this.InitializeComponent(); StopNative.Class1 c = new StopNative.Class1(); // create c++ component this.d3dView = new StopNative.D3DView(); this.d3dView.Initialize(this.swapChainPanel); // create c++ component DisplayInformation displayInfo = DisplayInformation.GetForCurrentView(); CoreWindow window = Window.Current.CoreWindow; window.VisibilityChanged += window_VisibilityChanged; displayInfo.DpiChanged += displayInfo_DpiChanged; displayInfo.OrientationChanged += displayInfo_OrientationChanged; DisplayInformation.DisplayContentsInvalidated += DisplayInformation_DisplayContentsInvalidated; this.swapChainPanel.CompositionScaleChanged += swapChainPanel_CompositionScaleChanged; this.swapChainPanel.SizeChanged += swapChainPanel_SizeChanged; Application.Current.Suspending += Current_Suspending; Application.Current.Resuming += Current_Resuming; var inputItemHandler = new WorkItemHandler((IAsyncAction inputAction) => { this.coreInput = this.swapChainPanel.CreateCoreIndependentInputSource( CoreInputDeviceTypes.Mouse | CoreInputDeviceTypes.Pen | CoreInputDeviceTypes.Touch); this.coreInput.PointerPressed += coreInput_PointerPressed; this.coreInput.PointerMoved += coreInput_PointerMoved; this.coreInput.PointerReleased += coreInput_PointerReleased; this.coreInput.PointerEntered += coreInput_PointerEntered; this.coreInput.PointerExited += coreInput_PointerExited; this.coreInput.Dispatcher.ProcessEvents(CoreProcessEventsOption.ProcessUntilQuit); }); var inputTask = ThreadPool.RunAsync(inputItemHandler, WorkItemPriority.High, WorkItemOptions.TimeSliced); }
/// <summary> /// Запуск процесса взаимодествия с сервером /// </summary> public async void Start() { SetInitialState(); _Terminating = false; bool res = await _Connection.Open(Host, Port, Password); if (!res) { await NotifyError(_Connection.Error); return; } WorkItemHandler communicator = delegate { ExecuteCommands(); }; ThreadPool.RunAsync(communicator, WorkItemPriority.High, WorkItemOptions.TimeSliced); CreateTimer(ViewUpdateInterval); _timer.Start(); }
public void StartRenderLoop() { if (m_renderLoopWorker?.Status == AsyncStatus.Started) { return; } WorkItemHandler workItemHandler = new WorkItemHandler(_ => { while (_.Status == AsyncStatus.Started) { Update(); if (Render()) { //present } } }); m_renderLoopWorker = ThreadPool.RunAsync(workItemHandler, WorkItemPriority.High, WorkItemOptions.TimeSliced); }
public void OnResuming() { // If the animation render loop is already running then do not start another thread. if (m_renderLoopWorker != null && m_renderLoopWorker.Status == AsyncStatus.Started) { return; } // Create a task that will be run on a background thread. var workItemHandler = new WorkItemHandler((action) => { // Calculate the updated frame and render once per vertical blanking interval. while (action.Status == AsyncStatus.Started) { lock (m_rendererLock) { Render(); } } }); // Run task on a dedicated high priority background thread. m_renderLoopWorker = ThreadPool.RunAsync(workItemHandler, WorkItemPriority.High, WorkItemOptions.TimeSliced); }
public ThreadClass(WorkItemHandler workItem) { this.WorkItem = workItem; Priority = WorkItemPriority.Normal; }
/// <summary> /// Instantiates a new DedicatedWorkThread given the WorkItemHandler. /// </summary> /// <param name="workItemHandler">Handler that will handle WorkItems.</param> /// <param name="keepAliveMillis">Milliseconds to keep the thread alive when idle, -1 to keep infinitely alive.</param> /// <param name="threadName">Optional name of the dedicated work thread.</param> public DedicatedWorkThread(WorkItemHandler <T> workItemHandler, int keepAliveMillis, string threadName = null) { this.workItemHandler = workItemHandler; this.keepAliveMillis = keepAliveMillis; this.ThreadName = threadName ?? Guid.NewGuid().ToString(); }
/// <summary> /// Creates a DedicatedWorkThread where configuration is done through AppSettings /// "{configName}.KeepAliveMs" and "{configName}.ThreadName". /// </summary> public DedicatedWorkThread(WorkItemHandler <T> workItemHandler, string configName) { this.workItemHandler = workItemHandler; this.keepAliveMillis = Int32.Parse(ConfigurationManager.AppSettings[configName + ".KeepAliveMs"] ?? "-1"); this.ThreadName = ConfigurationManager.AppSettings[configName + ".ThreadName"] ?? Guid.NewGuid().ToString(); }
void StartInputLoop() { // If the animation render loop is already running then do not start another thread. if (m_inputLoopWorker != null) { if (m_inputLoopWorker.Status == AsyncStatus.Started) { return; } else { m_inputLoopWorker.Close(); } } workItemHandler = new WorkItemHandler((IAsyncAction action) => { while (action.Status == AsyncStatus.Started) { var gamepads = Gamepad.Gamepads; if (gamepads.Count > 0 && activeGamePad == null) { // Get the Zero based first Gamepad activeGamePad = gamepads[0]; } if (activeGamePad != null) { timer.Tick(() => { GamepadReading reading = activeGamePad.GetCurrentReading(); double deltax; if (reading.LeftThumbstickX > THUMBSTICK_DEADZONE || reading.LeftThumbstickX < -THUMBSTICK_DEADZONE) { deltax = reading.LeftThumbstickX * reading.LeftThumbstickX * reading.LeftThumbstickX; } else { deltax = 0.0f; } double deltay; if (reading.LeftThumbstickY > THUMBSTICK_DEADZONE || reading.LeftThumbstickY < -THUMBSTICK_DEADZONE) { deltay = reading.LeftThumbstickY * reading.LeftThumbstickY * reading.LeftThumbstickY; } else { deltay = 0.0f; } double rotationX = deltax * rotationdelta; double rotationY = deltay * rotationdelta; pitch += rotationY; heading += rotationX; // Limit pitch to straight up or straight down. videoProjection.ViewOrientation = Helpers.CreateFromHeadingPitchRoll(heading, pitch, 0); }); } } }); m_inputLoopWorker = ThreadPool.RunAsync(workItemHandler, WorkItemPriority.High, WorkItemOptions.None); }
static void Main() { WorkItemHandler handler = new WorkItemHandler(); handler.UpdateProjectTestCases(); }
public static IAsyncAction RunAsync (WorkItemHandler handler, WorkItemPriority priority) { return RunAsync (handler); }
private async void QueueWorkItem(WorkItemHandler action) { await ThreadPool.RunAsync(action); }
private async void ThreadPoolButton_Click(object sender, RoutedEventArgs e) { var workItemHandler = new WorkItemHandler((arg) => { GetReading(); }); await ThreadPool.RunAsync(workItemHandler); }
public GitBranchHandler() { ItemHandler = new WorkItemHandler(); commandHandler = new GitCommandHandler(); }