public MockTransport(Uri uri) { this.connectedUri = uri; Tracer.Debug("Creating Async Response task"); asyncResponseTask = DefaultThreadPools.DefaultTaskRunnerFactory.CreateTaskRunner(new AsyncResponseTask(this), "ActiveMQ MockTransport Worker: " + this.GetHashCode().ToString()); }
void runTask(ITestTask task) { var taskRunner = new TaskRunner(); var runResult = taskRunner.Run(task); // 20150112 // task.TaskFinished = true task.TaskStatus = runResult ? TestTaskStatuses.CompletedSuccessfully : TestTaskStatuses.Interrupted; }
public void SetUp() { _tasks = CreateTasks(); _taskExecutor = new Mock<ITaskExecutor>(); _taskRunner = new TaskRunner(_taskExecutor.Object); }
public ProjectModel(TaskRunner runner, OptionsModel options) { _runner = runner; _options = options; _runner.TaskComplete += new Action<ITask, Exception>(OnTaskComplete); _depFileSystemWatchers = new Dependent(UpdateFileSystemWatchers); _updater = new GuiUpdateHelper(_depFileSystemWatchers); }
public void TaskCanBeInvokedWithNameInsensitiveOfCase() { var task = new MockTask {FullName = "The.Full.Path.To.Task"}; var runner = new TaskRunner(); AssertTaskIsInvokedWithName("the.full.path.to.task", runner, task); AssertTaskIsInvokedWithName("task", runner, task); }
static void InitInstance() { _instance = new TaskRunner(); #if UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_IPHONE || UNITY_ANDROID || UNITY_EDITOR _instance._runner = new MonoRunner(); #else _instance._runner = new MultiThreadRunner(); #endif _instance._taskRoutinePool = new TaskRoutinePool(_instance._runner); }
public void CannotBeInvokedTaskByPartialNameWithoutSpecificName() { var task = new MockTask {FullName = "The.Full.Path.To.Task"}; var runner = new TaskRunner(); AssertTaskIsNotInvokedWithName("The.Full.Path.To", runner, task); AssertTaskIsNotInvokedWithName("Full.Path.To", runner, task); AssertTaskIsNotInvokedWithName("Path.To", runner, task); AssertTaskIsNotInvokedWithName("To", runner, task); }
public void InvokesTaskByWholeName() { var task = new MockTask {FullName = "asdf"}; var runner = new TaskRunner(); var taskParameters = new TaskParameters(new Dictionary<string, string>()); runner.RunTask("asdf", taskParameters, new [] {task}); Assert.That(task.WasInvoked, Is.True); Assert.That(task.WasInvokedWithTaskParameters, Is.SameAs(taskParameters)); }
public void CanInvokeTaskByPartialNames() { var task = new MockTask {FullName = "The.Full.Path.To.Task"}; var runner = new TaskRunner(); AssertTaskIsInvokedWithName("The.Full.Path.To.Task", runner, task); AssertTaskIsInvokedWithName("Full.Path.To.Task", runner, task); AssertTaskIsInvokedWithName("Path.To.Task", runner, task); AssertTaskIsInvokedWithName("To.Task", runner, task); AssertTaskIsInvokedWithName("Task", runner, task); }
public void Destroy() { Stop(); if (_runner != null) { if (Application.isPlaying) GameObject.Destroy(_runner.gameObject); else GameObject.DestroyImmediate(_runner.gameObject); } _instance = null; }
public void Wakeup() { TaskRunner taskRunner = this.taskRunner; lock(messageQueue.SyncRoot) { if(this.taskRunner == null) { this.taskRunner = DefaultThreadPools.DefaultTaskRunnerFactory.CreateTaskRunner(this); } taskRunner = this.taskRunner; } taskRunner.Wakeup(); }
public void Setup() { serialTasks1 = new SerialTasks(); parallelTasks1 = new ParallelTasks(); serialTasks2 = new SerialTasks(); parallelTasks2 = new ParallelTasks(); task1 = new Task(15); task2 = new Task(5); iterable1 = new Enumerable(15); iterable2 = new Enumerable(5); iterations = 0; _taskRunner = TaskRunner.Instance; }
/// <summary> /// Initialises a new instance of the <see cref="Worker"/> class with /// the provided values. /// </summary> /// <param name="url">The URL.</param> /// <param name="agentKey">The agent key.</param> /// <param name="iisChecks">A value indicating whether or not to perform IIS checks.</param> /// <param name="pluginDirectory">The plugin directory.</param> /// <param name="mongoDBConnectionString">The MongoDB connection string.</param> /// <param name="sqlServerStatus">A value indicating whether or not to perform SQL Server checks.</param> public Worker(string url, string agentKey, bool iisChecks, string pluginDirectory, string mongoDBConnectionString, bool mongoDBDBStats, bool mongoDBReplSet, bool sqlServerStatus, string customPrefix, bool eventViewer) { Url = url; AgentKey = agentKey; IISChecks = iisChecks; PluginDirectory = pluginDirectory; MongoDBConnectionString = mongoDBConnectionString; MongoDBDBStats = mongoDBDBStats; MongoDBReplSet = mongoDBReplSet; SQLServerStatus = sqlServerStatus; CustomPrefix = customPrefix; EventViewer = eventViewer; _runner = new TaskRunner(); _runner.AddTask(new WriteAgentConfigurationTask( new AgentConfiguration(Url, AgentKey, IISChecks, PluginDirectory, MongoDBConnectionString, MongoDBDBStats, MongoDBReplSet, SQLServerStatus, CustomPrefix, EventViewer) )); _runner.AddTask(new StopServiceTask()); _runner.AddTask(new StartServiceTask()); _runner.TaskCompleted += Runner_TaskCompleted; }
// Execute one or more turns for this activation. // This method is always called in a single-threaded environment -- that is, no more than one // thread will be in this method at once -- but other asynch threads may still be queueing tasks, etc. public void Execute() { lock (lockable) { if (state == WorkGroupStatus.Shutdown) { if (!IsActive) { return; // Don't mind if no work has been queued to this work group yet. } ReportWorkGroupProblemWithBacktrace( "Cannot execute work items in a work item group that is in a shutdown state.", ErrorCode.SchedulerNotExecuteWhenShutdown); // Throws InvalidOperationException return; } state = WorkGroupStatus.Running; } var thread = WorkerPoolThread.CurrentWorkerThread; try { // Process multiple items -- drain the applicationMessageQueue (up to max items) for this physical activation int count = 0; var stopwatch = new Stopwatch(); stopwatch.Start(); do { lock (lockable) { if (state == WorkGroupStatus.Shutdown) { if (WorkItemCount > 0) { log.Warn(ErrorCode.SchedulerSkipWorkStopping, "Thread {0} is exiting work loop due to Shutdown state {1} while still having {2} work items in the queue.", thread.ToString(), this.ToString(), WorkItemCount); } else if (log.IsVerbose) { log.Verbose("Thread {0} is exiting work loop due to Shutdown state {1}. Has {2} work items in the queue.", thread.ToString(), this.ToString(), WorkItemCount); } break; } // Check the cancellation token (means that the silo is stopping) if (thread.CancelToken.IsCancellationRequested) { log.Warn(ErrorCode.SchedulerSkipWorkCancelled, "Thread {0} is exiting work loop due to cancellation token. WorkItemGroup: {1}, Have {2} work items in the queue.", thread.ToString(), this.ToString(), WorkItemCount); break; } } // Get the first Work Item on the list Task task; lock (lockable) { if (workItems.Count > 0) { task = workItems.Dequeue(); } else // If the list is empty, then we're done { break; } } #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectGlobalShedulerStats) { SchedulerStatisticsGroup.OnWorkItemDequeue(); } #endif #if DEBUG if (log.IsVerbose2) { log.Verbose2("About to execute task {0} in SchedulingContext={1}", task, SchedulingContext); } #endif var taskStart = stopwatch.Elapsed; try { thread.CurrentTask = task; #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectTurnsStats) { SchedulerStatisticsGroup.OnTurnExecutionStartsByWorkGroup(workItemGroupStatisticsNumber, thread.WorkerThreadStatisticsNumber, SchedulingContext); } #endif TaskRunner.RunTask(task); } catch (Exception ex) { log.Error(ErrorCode.SchedulerExceptionFromExecute, String.Format("Worker thread caught an exception thrown from Execute by task {0}", task), ex); throw; } finally { #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectTurnsStats) { SchedulerStatisticsGroup.OnTurnExecutionEnd(Utils.Since(thread.CurrentStateStarted)); } if (StatisticsCollector.CollectThreadTimeTrackingStats) { thread.threadTracking.IncrementNumberOfProcessed(); } #endif totalItemsProcessed++; var taskLength = stopwatch.Elapsed - taskStart; if (taskLength > OrleansTaskScheduler.TurnWarningLengthThreshold) { SchedulerStatisticsGroup.NumLongRunningTurns.Increment(); log.Warn(ErrorCode.SchedulerTurnTooLong3, "Task {0} in WorkGroup {1} took elapsed time {2:g} for execution, which is longer than {3}. Running on thread {4}", OrleansTaskExtentions.ToString(task), SchedulingContext.ToString(), taskLength, OrleansTaskScheduler.TurnWarningLengthThreshold, thread.ToString()); } thread.CurrentTask = null; } count++; }while (((MaxWorkItemsPerTurn <= 0) || (count <= MaxWorkItemsPerTurn)) && ((ActivationSchedulingQuantum <= TimeSpan.Zero) || (stopwatch.Elapsed < ActivationSchedulingQuantum))); stopwatch.Stop(); } catch (Exception ex) { log.Error(ErrorCode.Runtime_Error_100032, String.Format("Worker thread {0} caught an exception thrown from IWorkItem.Execute", thread), ex); } finally { // Now we're not Running anymore. // If we left work items on our run list, we're Runnable, and need to go back on the silo run queue; // If our run list is empty, then we're waiting. lock (lockable) { if (state != WorkGroupStatus.Shutdown) { if (WorkItemCount > 0) { state = WorkGroupStatus.Runnable; masterScheduler.RunQueue.Add(this); } else { state = WorkGroupStatus.Waiting; } } } } }
protected override void OnPageEnter_Finishing() { // OK button does Cancel until processing finished. Wizard.OKButtonText = Translator.Translate("TXT_CANCEL"); Wizard.ShowRepeatWizard = false; Wizard.ShowMovementButtons = false; Wizard.ShowOKButton = true; lblWizardResults.Text = Translator.Translate("TXT_WIZTASKSRUNNING"); _errorsFound = false; tvResults.Visible = _errorsFound; // Execute wizard if (BkgTask != null) { BkgTask.Reset(); // Resubscribe for task events BkgTask.TaskProgress -= new TaskProgressHandler(task_TaskProgress); BkgTask.TaskFinished -= new TaskFinishedHandler(task_TaskFinished); BkgTask.TaskStepInit -= new TaskStepInitHandler(task_TaskStepInit); BkgTask.TaskProgress += new TaskProgressHandler(task_TaskProgress); BkgTask.TaskFinished += new TaskFinishedHandler(task_TaskFinished); BkgTask.TaskStepInit += new TaskStepInitHandler(task_TaskStepInit); tvResults.Nodes.Clear(); pbProgress.Visible = true; pbProgress.Value = 0; if (BkgTask.TotalSteps > 1) { pbProgress.Maximum = BkgTask.TotalSteps; //pbProgress.Style = ProgressBarStyle.Continuous; } else { pbProgress.Maximum = 1; //pbProgress.Style = ProgressBarStyle.Marquee; } _runner = new TaskRunner(BkgTask); _runner.Run(); } }
static void InitInstance() { GameObject go = GameObject.Find("TaskRunner"); if (go == null) { go = new GameObject("TaskRunner"); GameObject.DontDestroyOnLoad(go); } _instance = new TaskRunner(); _instance._runner = go.AddComponent<MonoTask>(); }
protected virtual void OnClientSocketClosed(object sender, EventArgs e) { TaskRunner.Stop(); }
private void OnEnable() { taskRunner = ((TaskRunner)target); }
private static void AssertTaskIsInvokedWithName(string taskName, TaskRunner runner, MockTask task) { runner.RunTask(taskName, new TaskParameters(new Dictionary <string, string>()), new[] { task }); Assert.That(task.WasInvoked, Is.True); }
protected virtual void OnChannelStreamingStart(object sender, ProtocolEventArgs <ChannelStreamingStart> e) { e.Message.Channels.ForEach(ChannelStreamingInfo.Add); TaskRunner.Start(); }
private TestHostContext CreateTestContext([CallerMemberName] String testName = "") { var hc = new TestHostContext(this, testName); _jobEc = new Agent.Worker.ExecutionContext(); _taskManager = new Mock <ITaskManager>(); _jobServerQueue = new Mock <IJobServerQueue>(); _config = new Mock <IConfigurationStore>(); _logger = new Mock <IPagingLogger>(); _proxy = new Mock <IVstsAgentWebProxy>(); _cert = new Mock <IAgentCertificateManager>(); _express = new Mock <IExpressionManager>(); _containerProvider = new Mock <IContainerOperationProvider>(); TaskRunner step1 = new TaskRunner(); TaskRunner step2 = new TaskRunner(); TaskRunner step3 = new TaskRunner(); TaskRunner step4 = new TaskRunner(); TaskRunner step5 = new TaskRunner(); TaskRunner step6 = new TaskRunner(); TaskRunner step7 = new TaskRunner(); TaskRunner step8 = new TaskRunner(); TaskRunner step9 = new TaskRunner(); TaskRunner step10 = new TaskRunner(); TaskRunner step11 = new TaskRunner(); TaskRunner step12 = new TaskRunner(); _logger.Setup(x => x.Setup(It.IsAny <Guid>(), It.IsAny <Guid>())); var settings = new AgentSettings { AgentId = 1, AgentName = "agent1", ServerUrl = "https://test.visualstudio.com", WorkFolder = "_work", }; _config.Setup(x => x.GetSettings()) .Returns(settings); _proxy.Setup(x => x.ProxyAddress) .Returns(string.Empty); if (_tokenSource != null) { _tokenSource.Dispose(); _tokenSource = null; } _tokenSource = new CancellationTokenSource(); TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference(); TimelineReference timeline = new Timeline(Guid.NewGuid()); JobEnvironment environment = new JobEnvironment(); environment.Variables[Constants.Variables.System.Culture] = "en-US"; environment.SystemConnection = new ServiceEndpoint() { Name = WellKnownServiceEndpointNames.SystemVssConnection, Url = new Uri("https://test.visualstudio.com"), Authorization = new EndpointAuthorization() { Scheme = "Test", } }; environment.SystemConnection.Authorization.Parameters["AccessToken"] = "token"; List <TaskInstance> tasks = new List <TaskInstance>() { new TaskInstance() { InstanceId = Guid.NewGuid(), DisplayName = "task1", }, new TaskInstance() { InstanceId = Guid.NewGuid(), DisplayName = "task2", }, new TaskInstance() { InstanceId = Guid.NewGuid(), DisplayName = "task3", }, new TaskInstance() { InstanceId = Guid.NewGuid(), DisplayName = "task4", }, new TaskInstance() { InstanceId = Guid.NewGuid(), DisplayName = "task5", }, new TaskInstance() { InstanceId = Guid.NewGuid(), DisplayName = "task6", }, new TaskInstance() { InstanceId = Guid.NewGuid(), DisplayName = "task7", }, }; Guid JobId = Guid.NewGuid(); _message = Pipelines.AgentJobRequestMessageUtil.Convert(new AgentJobRequestMessage(plan, timeline, JobId, testName, testName, environment, tasks)); _initResult.PreJobSteps.Clear(); _initResult.JobSteps.Clear(); _initResult.PostJobStep.Clear(); _taskManager.Setup(x => x.DownloadAsync(It.IsAny <IExecutionContext>(), It.IsAny <IEnumerable <Pipelines.TaskStep> >())) .Returns(Task.CompletedTask); _taskManager.Setup(x => x.Load(It.Is <Pipelines.TaskStep>(t => t.DisplayName == "task1"))) .Returns(new Definition() { Data = new DefinitionData() { PreJobExecution = null, Execution = new ExecutionData(), PostJobExecution = null, }, }); _taskManager.Setup(x => x.Load(It.Is <Pipelines.TaskStep>(t => t.DisplayName == "task2"))) .Returns(new Definition() { Data = new DefinitionData() { PreJobExecution = new ExecutionData(), Execution = new ExecutionData(), PostJobExecution = new ExecutionData(), }, }); _taskManager.Setup(x => x.Load(It.Is <Pipelines.TaskStep>(t => t.DisplayName == "task3"))) .Returns(new Definition() { Data = new DefinitionData() { PreJobExecution = new ExecutionData(), Execution = null, PostJobExecution = new ExecutionData(), }, }); _taskManager.Setup(x => x.Load(It.Is <Pipelines.TaskStep>(t => t.DisplayName == "task4"))) .Returns(new Definition() { Data = new DefinitionData() { PreJobExecution = new ExecutionData(), Execution = null, PostJobExecution = null, }, }); _taskManager.Setup(x => x.Load(It.Is <Pipelines.TaskStep>(t => t.DisplayName == "task5"))) .Returns(new Definition() { Data = new DefinitionData() { PreJobExecution = null, Execution = null, PostJobExecution = new ExecutionData(), }, }); _taskManager.Setup(x => x.Load(It.Is <Pipelines.TaskStep>(t => t.DisplayName == "task6"))) .Returns(new Definition() { Data = new DefinitionData() { PreJobExecution = new ExecutionData(), Execution = new ExecutionData(), PostJobExecution = null, }, }); _taskManager.Setup(x => x.Load(It.Is <Pipelines.TaskStep>(t => t.DisplayName == "task7"))) .Returns(new Definition() { Data = new DefinitionData() { PreJobExecution = null, Execution = new ExecutionData(), PostJobExecution = new ExecutionData(), }, }); hc.SetSingleton(_taskManager.Object); hc.SetSingleton(_config.Object); hc.SetSingleton(_jobServerQueue.Object); hc.SetSingleton(_proxy.Object); hc.SetSingleton(_cert.Object); hc.SetSingleton(_express.Object); hc.SetSingleton(_containerProvider.Object); hc.EnqueueInstance <IPagingLogger>(_logger.Object); // jobcontext logger hc.EnqueueInstance <IPagingLogger>(_logger.Object); // init step logger hc.EnqueueInstance <IPagingLogger>(_logger.Object); // step 1 hc.EnqueueInstance <IPagingLogger>(_logger.Object); hc.EnqueueInstance <IPagingLogger>(_logger.Object); hc.EnqueueInstance <IPagingLogger>(_logger.Object); hc.EnqueueInstance <IPagingLogger>(_logger.Object); hc.EnqueueInstance <IPagingLogger>(_logger.Object); hc.EnqueueInstance <IPagingLogger>(_logger.Object); hc.EnqueueInstance <IPagingLogger>(_logger.Object); hc.EnqueueInstance <IPagingLogger>(_logger.Object); hc.EnqueueInstance <IPagingLogger>(_logger.Object); hc.EnqueueInstance <IPagingLogger>(_logger.Object); hc.EnqueueInstance <IPagingLogger>(_logger.Object); // step 12 hc.EnqueueInstance <ITaskRunner>(step1); hc.EnqueueInstance <ITaskRunner>(step2); hc.EnqueueInstance <ITaskRunner>(step3); hc.EnqueueInstance <ITaskRunner>(step4); hc.EnqueueInstance <ITaskRunner>(step5); hc.EnqueueInstance <ITaskRunner>(step6); hc.EnqueueInstance <ITaskRunner>(step7); hc.EnqueueInstance <ITaskRunner>(step8); hc.EnqueueInstance <ITaskRunner>(step9); hc.EnqueueInstance <ITaskRunner>(step10); hc.EnqueueInstance <ITaskRunner>(step11); hc.EnqueueInstance <ITaskRunner>(step12); _jobEc.Initialize(hc); _jobEc.InitializeJob(_message, _tokenSource.Token); return(hc); }
public async Task <int> ReadAllAsync(byte[] buffer, int offset, int length) { return(await TaskRunner.Run(() => ReadAll(buffer, offset, length))); }
private static void AssertTaskIsInvokedWithName(string taskName, TaskRunner runner, MockTask task) { runner.RunTask(taskName, new TaskParameters(new Dictionary<string, string>()), new[] {task}); Assert.That(task.WasInvoked, Is.True); }
private static void AssertTaskIsNotInvokedWithName(string taskName, TaskRunner runner, MockTask task) { Assert.That( () => runner.RunTask(taskName, new TaskParameters(new Dictionary<string, string>()), new[] {task}), Throws.InstanceOf<NoMatchingTaskException>()); }
private void OnPing(byte[] obj) { _log.Trace("Ping received"); TaskRunner.RunInBackground(() => _webSocket.SendPong(obj)).LogAndIgnoreExceptions(_log); }
private static Dictionary <Assembly, HashSet <Type> > GetAssemblyTypes(List <Assembly> assemblies, bool allowMultithreadedInitialization = false) { var dictionary = new Dictionary <Assembly, HashSet <Type> >(); if (allowMultithreadedInitialization) { const int PreferredNumberOfThreads = 20; var tasks = new List <Task <List <KeyValuePair <Assembly, HashSet <Type> > > > >(); var taskLists = new List <List <Assembly> >(); var assemblyCount = assemblies.Count; var assembliesPerBatch = (int)Math.Ceiling(assemblyCount / (double)PreferredNumberOfThreads); var batchCount = (int)Math.Ceiling(assemblyCount / (double)assembliesPerBatch); for (var i = 0; i < batchCount; i++) { var taskList = new List <Assembly>(); var startIndex = (assembliesPerBatch * i); var endIndex = Math.Min(assembliesPerBatch * (i + 1), assemblyCount); for (var j = startIndex; j < endIndex; j++) { taskList.Add(assemblies[j]); } taskLists.Add(taskList); } for (var i = 0; i < taskLists.Count; i++) { var taskList = taskLists[i]; var task = TaskRunner.Run(() => { var taskResults = new List <KeyValuePair <Assembly, HashSet <Type> > >(); foreach (var assembly in taskList) { var assemblyTypes = assembly.GetAllTypesSafely(); taskResults.Add(new KeyValuePair <Assembly, HashSet <Type> >(assembly, new HashSet <Type>(assemblyTypes))); } return(taskResults); }); tasks.Add(task); } var waitTask = Task.WhenAll(tasks); waitTask.Wait(); foreach (var task in tasks) { var results = task.Result; foreach (var result in results) { dictionary[result.Key] = result.Value; } } } else { var types = (from assembly in assemblies select new KeyValuePair <Assembly, HashSet <Type> >(assembly, new HashSet <Type>(assembly.GetAllTypesSafely()))); var results = types.AsParallel(); return(results.ToDictionary(p => p.Key, p => p.Value)); } return(dictionary); }
public override Task <bool> OpenAsync() { Open(); return(TaskRunner.Run(() => true)); }
public static async Task <TResult> RunWithResultAsync <TResult>(Func <Task <TResult> > method) { return(await await TaskRunner.RunAsync(async() => await method())); }
public async Task <int> ReadAllAsync(byte[] buffer, int offset, int length, CancellationToken token) { return(await TaskRunner.Run(() => ReadAll(buffer, offset, length), token)); }
public static async Task RunAsync(Action method) { await TaskRunner.RunAsync(method); }
/// <summary> /// Runs a UniTask and calls onComplete when done. /// </summary> /// <param name="task"></param> /// <param name="onComplete"></param> public static void Run(this UniTask task, Action <object> onComplete = null) { var taskRunner = new TaskRunner(task, onComplete); }
private static void AssertTaskIsNotInvokedWithName(string taskName, TaskRunner runner, MockTask task) { Assert.That( () => runner.RunTask(taskName, new TaskParameters(new Dictionary <string, string>()), new[] { task }), Throws.InstanceOf <NoMatchingTaskException>()); }
public override async Task Initalize() { await base.Initalize(); TaskRunner.Run(() => RevenueProposalLoop()); }
protected virtual void OnChannelStreamingStop(object sender, ProtocolEventArgs <ChannelStreamingStop> e) { TaskRunner.Stop(); }
public ProjectModel(TaskRunner runner) : this(runner, new OptionsModel()) { }
/// <summary> /// Runs the flusher thread. /// </summary> public void RunThread() { TaskRunner.Run(Run); }
public void Stop() { if(messageQueue.Running) { messageQueue.Stop(); TaskRunner taskRunner = this.taskRunner; if(taskRunner != null) { this.taskRunner = null; taskRunner.Shutdown(); } } }
public void DeleteAsync <T>(T entity, Action callback, Action <Exception> errorCallback = null) { TaskRunner.Run(() => Delete(entity), callback, errorCallback); }
void ICompositionRoot.OnContextDestroyed() { _enginesRoot.Dispose(); TaskRunner.StopAndCleanupAllDefaultSchedulers(); }
//protected override bool ProcessDialogKey(Keys keyData) //{ // if (keyData == Keys.Escape || keyData == Keys.Enter) // { // Wizard.DialogResult = DialogResult.OK; // return true; // } // return base.ProcessDialogKey(keyData); //} void hostForm_FormClosing(object sender, FormClosingEventArgs e) { if (Wizard == null) // not the active page return; bool mustClose = true; if (_runner != null && BkgTask != null) { if (BkgTask != null) { if (BkgTask.IsFinished) { mustClose = !Wizard.RepeatWizard; } else { mustClose = _runner.Cancel(); } } if (mustClose) { _runner.Dispose(); _runner = null; } else if (FinishPageExit != null) { FinishPageExit(this, e); } } e.Cancel = !mustClose; }
public void ConcurrentSendAndReceive(byte[][] serverMessages, byte[][] clientMessages) { var serverRecevied = new List <byte[]>(); var clientReceived = new List <byte[]>(); var serverTask = TaskRunner.RunInBackground(async() => { WriteLog($"Starting server"); var server = RegisterDisposable(CreateServer()); await server.StartAsync().ConfigureAwaitWithTimeout(Timeout5Sec); WriteLog($"Server started"); using (var serverConnection = RegisterDisposable(await server.In.ReadAsync().ConfigureAwait(false))) { var receiveTask = TaskRunner.RunInBackground(async() => { while (true) { var msg = await serverConnection.In.TryReadAsync().ConfigureAwait(false); if (msg.HasValue) { WriteLog($"Server received message of length {msg.Value.Count}"); serverRecevied.Add(msg.Value.ToArray()); } else { WriteLog("Server receive completed"); break; } } }); var sendTask = TaskRunner.RunInBackground(async() => { foreach (var msg in serverMessages) { WriteLog($"Server sending message of length {msg.Length}"); await serverConnection.Out.WriteAsync(PooledBuffer.Get(msg)).ConfigureAwait(false); } serverConnection.Out.TryComplete(); WriteLog("Server send completed"); }); await Task.WhenAll(sendTask, receiveTask, serverConnection.Completion).ConfigureAwait(false); WriteLog("Server completed"); } }); var clientTask = TaskRunner.RunInBackground(async() => { try { var clientFactory = CreateClient(); WriteLog("Connecting client"); using (var connection = RegisterDisposable(await clientFactory.ConnectAsync(BrokerWorkingDir).ConfigureAwait(false))) { WriteLog($"Client connected"); var receiveTask = TaskRunner.RunInBackground(async() => { while (true) { var msg = await connection.In.TryReadAsync().ConfigureAwait(false); if (msg.HasValue) { WriteLog($"Client received message of length {msg.Value.Count}"); clientReceived.Add(msg.Value.ToArray()); } else { WriteLog("Client receive completed"); break; } } }); var sendTask = TaskRunner.RunInBackground(async() => { foreach (var msg in clientMessages) { WriteLog($"Client sending message of length {msg.Length}"); await connection.Out.WriteAsync(PooledBuffer.Get(msg)).ConfigureAwait(false); } connection.Out.TryComplete(); WriteLog("Client send completed"); }); await Task.WhenAll(sendTask, receiveTask, connection.Completion).ConfigureAwait(false); WriteLog("Client completed"); } } catch (Exception ex) { WriteLog("Client exception: " + ex); throw; } }); Should.CompleteIn(Task.WhenAny(serverTask, clientTask).Unwrap(), TimeoutConstants.Timeout10Sec); Should.CompleteIn(Task.WhenAll(serverTask, clientTask), TimeoutConstants.Timeout10Sec); WriteLog("All completed"); serverRecevied.Count.ShouldBe(clientMessages.Length); clientReceived.Count.ShouldBe(serverMessages.Length); for (var i = 0; i < clientMessages.Length; i++) { serverRecevied[i].ShouldBe(clientMessages[i]); } for (var i = 0; i < serverMessages.Length; i++) { clientReceived[i].ShouldBe(serverMessages[i]); } }
/// <summary> /// Runs a UniTask and calls onComplete when done. /// </summary> /// <param name="task"></param> /// <param name="onComplete"></param> /// <typeparam name="T"></typeparam> public static void Run <T>(this UniTask <T> task, Action <T> onComplete = null) { var taskRunner = new TaskRunner <T>(task, onComplete); }
public Task GracefulShutdown(TimeSpan gracePeriod) { Shutdown(gracePeriod); return(TaskRunner.Delay(gracePeriod)); }
public MainForm() { InitializeComponent(); runner = new TaskRunner<Void>(LongRunningMethod); }
public void TestLocalListenMultithreaded() { const int threadCnt = 20; const int runSeconds = 20; var messaging = _grid1.GetMessaging(); var senders = TaskRunner.Run(() => TestUtils.RunMultiThreaded(() => { messaging.Send(NextMessage()); Thread.Sleep(50); }, threadCnt, runSeconds)); var sharedReceived = 0; var sharedListener = new MessageListener <string>((id, x) => { Interlocked.Increment(ref sharedReceived); Thread.MemoryBarrier(); return(true); }); TestUtils.RunMultiThreaded(() => { // Check that listen/stop work concurrently messaging.LocalListen(sharedListener); for (int i = 0; i < 100; i++) { messaging.LocalListen(sharedListener); messaging.StopLocalListen(sharedListener); } var localReceived = 0; var stopLocal = 0; var localListener = new MessageListener <string>((id, x) => { Interlocked.Increment(ref localReceived); Thread.MemoryBarrier(); return(Thread.VolatileRead(ref stopLocal) == 0); }); messaging.LocalListen(localListener); Thread.Sleep(100); Thread.VolatileWrite(ref stopLocal, 1); Thread.Sleep(1000); var result = Thread.VolatileRead(ref localReceived); Thread.Sleep(100); // Check that unsubscription worked properly Assert.AreEqual(result, Thread.VolatileRead(ref localReceived)); messaging.StopLocalListen(sharedListener); }, threadCnt, runSeconds); senders.Wait(); Thread.Sleep(100); var sharedResult = Thread.VolatileRead(ref sharedReceived); messaging.Send(NextMessage()); Thread.Sleep(MessagingTestHelper.SleepTimeout); // Check that unsubscription worked properly Assert.AreEqual(sharedResult, Thread.VolatileRead(ref sharedReceived)); }
public async Task HandleAsync(IInvocationStart request, IAppConnection sourceConnection, ITransportChannel sourceChannel) { IAppConnection targetConnection = null; ITransportChannel targetChannel = null; InvocationDescriptor callDescriptor = null; var startMs = _stopwatch.ElapsedMilliseconds; try { Log.Info("Handling invocation {0} from {{{1}}}: {{{2}}}", sourceChannel.Id, sourceConnection, request); targetConnection = await request.Target.Handle(_resolveTargetConnectionHandler, sourceConnection).ConfigureAwait(false); targetChannel = await targetConnection.CreateChannelAsync().ConfigureAwait(false); Log.Debug("Created channel {0} for invocation {1} from {{{2}}} to {{{3}}}: {{{4}}}", targetChannel.Id, sourceChannel.Id, sourceConnection, targetConnection, request); using (var invocationStarting = _protocolMessageFactory.CreateInvocationStarting()) { var serialized = _protocolSerializer.Serialize(invocationStarting); try { await sourceChannel.Out.WriteAsync(new TransportMessageFrame(serialized)).ConfigureAwait(false); Log.Trace("Sent starting event for invocation {0}", sourceChannel.Id); } catch { serialized.Dispose(); throw; } } using (var invocationRequested = request.Target.Handle(_createRequestHandler, sourceConnection)) { startMs = _stopwatch.ElapsedMilliseconds; callDescriptor = new InvocationDescriptor( sourceConnection.Info, targetConnection.Info, invocationRequested.ServiceId, invocationRequested.ServiceAlias.GetValueOrDefault(), invocationRequested.MethodId); _appLifecycleManager.OnInvocationStarted(new InvocationStartedEventDescriptor(callDescriptor)); var serialized = _protocolSerializer.Serialize(invocationRequested); try { await targetChannel.Out.WriteAsync(new TransportMessageFrame(serialized)).ConfigureAwait(false); Log.Trace("Sent requested event for invocation {0} to {1}", targetChannel.Id, targetConnection); } catch { serialized.Dispose(); throw; } } var propagateTask1 = TaskRunner.RunInBackground(() => PropagateAsync(sourceChannel.In, targetChannel.Out)); var propagateTask2 = TaskRunner.RunInBackground(() => PropagateAsync(targetChannel.In, sourceChannel.Out)); await Task.WhenAll(propagateTask1, propagateTask2).ConfigureAwait(false); } catch (Exception ex) { sourceChannel.Out.TryTerminate(ex); targetChannel?.Out.TryTerminate(ex); throw; } finally { try { await Task .WhenAll( targetChannel?.In.ConsumeAsync((Action <TransportMessageFrame>)DisposeFrame).IgnoreExceptions() ?? TaskConstants.Completed, sourceChannel.In.ConsumeAsync((Action <TransportMessageFrame>)DisposeFrame).IgnoreExceptions(), targetChannel?.Completion ?? TaskConstants.Completed, sourceChannel.Completion) .ConfigureAwait(false); Log.Info("Completed invocation {0} from {{{1}}} to {{{2}}}: {{{3}}}", sourceChannel.Id, sourceConnection, targetConnection, request); OnActionFinished(callDescriptor, InvocationResult.Succeeded, startMs); } catch (OperationCanceledException) { Log.Info("Canceled invocation {0} from {{{1}}} to {{{2}}}: {{{3}}}", sourceChannel.Id, sourceConnection, targetConnection, request); OnActionFinished(callDescriptor, InvocationResult.Canceled, startMs); throw; } catch (Exception ex) { Log.Warn("Failed invocation {0} from {{{1}}} to {{{2}}}: {{{3}}}. Error: {4}", sourceChannel.Id, sourceConnection, targetConnection, request, ex.FormatTypeAndMessage()); OnActionFinished(callDescriptor, InvocationResult.Failed, startMs); throw; } } }
public void Reconnect(bool rebalance) { lock(reconnectMutex) { if(started) { if(reconnectTask == null) { Tracer.Debug("Creating reconnect task"); reconnectTask = DefaultThreadPools.DefaultTaskRunnerFactory.CreateTaskRunner(new FailoverTask(this), "ActiveMQ Failover Worker: " + this.GetHashCode().ToString()); } if(rebalance) { ITransport transport = connectedTransport.GetAndSet(null); if(transport != null) { transport.Command = disposedOnCommand; transport.Exception = disposedOnException; try { transport.Stop(); } catch(Exception ex) { ex.GetType(); // Ignore errors but this lets us see the error during debugging } } } Tracer.Debug("Waking up reconnect task"); try { reconnectTask.Wakeup(); } catch(ThreadInterruptedException) { } } else { Tracer.Debug("Reconnect was triggered but transport is not started yet. Wait for start to connect the transport."); } } }
public void Stop(TimeSpan timeout) { if(messageQueue.Running) { messageQueue.Stop(); TaskRunner taskRunner = this.taskRunner; if(taskRunner != null) { this.taskRunner = null; taskRunner.ShutdownWithAbort(timeout); } } }
public void Wakeup() { TaskRunner taskRunner = this.taskRunner; lock(messageQueue.SyncRoot) { if(this.taskRunner == null) { this.taskRunner = new DedicatedTaskRunner(this); } taskRunner = this.taskRunner; } taskRunner.Wakeup(); }
#pragma warning disable xUnit1026 // Theory methods should use all of their parameters public void SendMessagesInBothDirections(ChannelExchange[] cases) #pragma warning restore xUnit1026 // Theory methods should use all of their parameters { var serverSentMessageHashes = new List <List <byte[]> >(); var serverReceivedMessageHashes = new List <List <byte[]> >(); var clientSentMessageHashes = new List <List <byte[]> >(); var clientReceivedMessageHashes = new List <List <byte[]> >(); async Task HandleChannelAsync(ITransportChannel c, int[] send, List <byte[]> received, List <byte[]> sent) { Log.Info("Handling channel {0}", c.Id); var receiveTask = TaskRunner.RunInBackground( async() => { while (true) { var receivedMsg = await c.TryReceiveMessageAsync().ConfigureAwait(false); if (!receivedMsg.HasValue) { break; } lock (Md5) { received.Add(Md5.ComputeHash(receivedMsg.Value)); } } }); foreach (var length in send) { var msg = Random.GetRandomBytes(length); await c.SendMessageAsync(msg).ConfigureAwait(false); lock (Md5) { sent.Add(Md5.ComputeHash(msg)); } } c.Out.TryComplete(); await receiveTask.ConfigureAwait(false); Log.Info("Channel handling completed {0}. Received {1} messages.", c.Id, received.Count); } ITransportConnection clientConnection = null; ITransportConnection serverConnection = null; var serverTask = TaskRunner.RunInBackground( async() => { await Server.StartAsync().ConfigureAwait(false); serverConnection = await Server.CreateAsync().ConfigureAwait(false); Log.Info("Server connection created"); var channelTasks = new List <Task>(); foreach (var channelExchange in cases) { var channel = await serverConnection.CreateChannelAsync().ConfigureAwait(false); Log.Info("Server channel created"); var rec = new List <byte[]>(); var sent = new List <byte[]>(); clientReceivedMessageHashes.Add(rec); clientSentMessageHashes.Add(sent); channelTasks.Add(TaskRunner.RunInBackground(() => HandleChannelAsync(channel, channelExchange.ClientMessageLengths, rec, sent))); } await Task.WhenAll(channelTasks).ConfigureAwait(false); }); var clientTask = TaskRunner.RunInBackground( async() => { clientConnection = await Client.CreateAsync().ConfigureAwait(false); Log.Info("Client connection created"); var channelTasks = new List <Task>(); foreach (var channelExchange in cases) { var channel = await clientConnection.IncomingChannels.ReadAsync().ConfigureAwait(false); Log.Info("Client channel received"); var rec = new List <byte[]>(); var sent = new List <byte[]>(); serverReceivedMessageHashes.Add(rec); serverSentMessageHashes.Add(sent); channelTasks.Add(TaskRunner.RunInBackground(() => HandleChannelAsync(channel, channelExchange.ServerMessageLengths, rec, sent))); } await Task.WhenAll(channelTasks).ConfigureAwait(false); }); Should.CompleteIn(Task.WhenAll(serverTask, clientTask), TimeSpan.FromSeconds(10)); Should.CompleteIn(clientConnection.CompleteAsync(), Timeout1Sec); Should.CompleteIn(serverConnection.CompleteAsync(), Timeout1Sec); Log.Debug("Tasks completed"); serverReceivedMessageHashes.Count.ShouldBe(cases.Length); serverSentMessageHashes.Count.ShouldBe(cases.Length); clientReceivedMessageHashes.Count.ShouldBe(cases.Length); clientSentMessageHashes.Count.ShouldBe(cases.Length); for (int i = 0; i < serverReceivedMessageHashes.Count; i++) { serverReceivedMessageHashes[i].Count.ShouldBe(clientSentMessageHashes[i].Count); for (int j = 0; j < serverReceivedMessageHashes[i].Count; j++) { serverReceivedMessageHashes[i][j].ShouldBe(clientSentMessageHashes[i][j]); } } for (int i = 0; i < clientReceivedMessageHashes.Count; i++) { clientReceivedMessageHashes[i].Count.ShouldBe(serverSentMessageHashes[i].Count); for (int j = 0; j < clientReceivedMessageHashes[i].Count; j++) { clientReceivedMessageHashes[i][j].ShouldBe(serverSentMessageHashes[i][j]); } } }
public bool IsValid(ICredentials creds, out IToken token) { token = TaskRunner.RunSynchonously(IsValidAsync, creds); return(token != null); }
public TreeModel(TaskRunner runner, OptionsModel options) { _runner = runner; //_runner.TaskComplete += new Action<IRowModel>(Runner_TaskComplete); Options = options; }
public TaskRunnerDisplay(TaskRunner taskRunner, Form form, FormControls controls) { Form = form; Controls = controls; TaskRunner = taskRunner; }
static void InitInstance() { _instance = new TaskRunner(); _instance._runner = new MonoTaskRunner(); }
public static async Task <TResult> RunWithResultAsync <TResult>(Func <TResult> method) { return(await TaskRunner.RunAsync(method)); }
public FailoverTransport() { id = idCounter++; stateTracker.TrackTransactions = true; reconnectTask = DefaultThreadPools.DefaultTaskRunnerFactory.CreateTaskRunner( new FailoverTask(this), "ActiveMQ Failover Worker: " + this.GetHashCode().ToString()); }
public static async Task RunAsync(Func <Task> method) { await await TaskRunner.RunAsync(async() => await method()); }