当前位置: 首页>>代码示例>>C#>>正文


C# JobHost.Stop方法代码示例

本文整理汇总了C#中JobHost.Stop方法的典型用法代码示例。如果您正苦于以下问题:C# JobHost.Stop方法的具体用法?C# JobHost.Stop怎么用?C# JobHost.Stop使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在JobHost的用法示例。


在下文中一共展示了JobHost.Stop方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: EnsuresNoWorkIsDone

            public void EnsuresNoWorkIsDone()
            {
                var host = new JobHost();
                var task = new Task(() => { throw new InvalidOperationException("Hey, this is supposed to be shut down!"); });

                host.Stop(true);

                host.DoWork(task);
            }
开发者ID:regisbsb,项目名称:WebBackgrounder,代码行数:9,代码来源:JobHostFacts.cs

示例2: RunTimerJobTest

        private async Task RunTimerJobTest(Type jobClassType, Func<bool> condition)
        {
            TestTraceWriter testTrace = new TestTraceWriter(TraceLevel.Error);
            ExplicitTypeLocator locator = new ExplicitTypeLocator(jobClassType);
            JobHostConfiguration config = new JobHostConfiguration
            {
                TypeLocator = locator
            };
            config.UseTimers();
            config.Tracing.Tracers.Add(testTrace);
            JobHost host = new JobHost(config);

            host.Start();

            await TestHelpers.Await(() =>
            {
                return condition();
            });

            host.Stop();

            // ensure there were no errors
            Assert.Equal(0, testTrace.Events.Count);
        }
开发者ID:christopheranderson,项目名称:azure-webjobs-sdk-extensions,代码行数:24,代码来源:TimerTriggerEndToEndTests.cs

示例3: WaitsForTaskToComplete

            public void WaitsForTaskToComplete()
            {
                var host = new JobHost();
                var workTask = new Task(() => host.DoWork(new Task(() =>
                {
                    // Was getting inconsistent results with Thread.Sleep(100)
                    for (int i = 0; i < 100; i++)
                    {
                        Thread.Sleep(1);
                    }
                })));
                var beforeStop = DateTime.UtcNow;
                workTask.Start();
                while (workTask.Status != TaskStatus.Running)
                {
                    Thread.Sleep(1);
                }

                host.Stop(false);
                var afterStop = DateTime.UtcNow;

                // If Stop didn't wait, we'd expect after to be less than 100 ms larger than beforeStop
                Assert.True((afterStop - beforeStop).TotalMilliseconds >= 100);
            }
开发者ID:regisbsb,项目名称:WebBackgrounder,代码行数:24,代码来源:JobHostFacts.cs

示例4: StartAsync_WhenStopped_Throws

        public void StartAsync_WhenStopped_Throws()
        {
            // Arrange
            using (JobHost host = new JobHost(CreateConfiguration()))
            {
                host.Start();
                host.Stop();

                // Act & Assert
                ExceptionAssert.ThrowsInvalidOperation(() => host.StartAsync(), "Start has already been called.");
            }
        }
开发者ID:oaastest,项目名称:azure-webjobs-sdk,代码行数:12,代码来源:JobHostTests.cs

示例5: StopAsync_WhenStopped_DoesNotThrow

        public void StopAsync_WhenStopped_DoesNotThrow()
        {
            // Arrange
            using (JobHost host = new JobHost(CreateConfiguration()))
            {
                host.Start();
                host.Stop();

                // Act & Assert
                host.StopAsync().GetAwaiter().GetResult();
            }
        }
开发者ID:oaastest,项目名称:azure-webjobs-sdk,代码行数:12,代码来源:JobHostTests.cs

示例6: IndexingExceptions_CanBeHandledByTraceWriter

        public void IndexingExceptions_CanBeHandledByTraceWriter()
        {
            JobHostConfiguration config = new JobHostConfiguration();
            TestTraceWriter traceWriter = new TestTraceWriter(TraceLevel.Verbose);
            config.Tracing.Tracers.Add(traceWriter);
            config.TypeLocator = new FakeTypeLocator(typeof(BindingErrorsProgram));

            FunctionErrorTraceWriter errorTraceWriter = new FunctionErrorTraceWriter(TraceLevel.Error);
            config.Tracing.Tracers.Add(errorTraceWriter);

            JobHost host = new JobHost(config);
            host.Start();

            // verify the handled binding error
            FunctionIndexingException fex = errorTraceWriter.Errors.SingleOrDefault() as FunctionIndexingException;
            Assert.True(fex.Handled);
            Assert.Equal("BindingErrorsProgram.Invalid", fex.MethodName);

            // verify that the binding error was logged
            Assert.Equal(5, traceWriter.Traces.Count);
            TraceEvent traceEvent = traceWriter.Traces[0];
            Assert.Equal("Error indexing method 'BindingErrorsProgram.Invalid'", traceEvent.Message);
            Assert.Same(fex, traceEvent.Exception);
            Assert.Equal("Invalid container name: invalid$=+1", traceEvent.Exception.InnerException.Message);

            // verify that the valid function was still indexed
            traceEvent = traceWriter.Traces[1];
            Assert.True(traceEvent.Message.Contains("Found the following functions"));
            Assert.True(traceEvent.Message.Contains("BindingErrorsProgram.Valid"));

            // verify that the job host was started successfully
            traceEvent = traceWriter.Traces[4];
            Assert.Equal("Job host started", traceEvent.Message);

            host.Stop();
            host.Dispose();
        }
开发者ID:ConnorMcMahon,项目名称:azure-webjobs-sdk,代码行数:37,代码来源:JobHostTests.cs

示例7: BlobGetsProcessedOnlyOnce_SingleHost

        public void BlobGetsProcessedOnlyOnce_SingleHost()
        {
            TextWriter hold = Console.Out;
            StringWriter consoleOutput = new StringWriter();
            Console.SetOut(consoleOutput);

            CloudBlockBlob blob = _testContainer.GetBlockBlobReference(BlobName);
            blob.UploadText("0");

            int timeToProcess;

            // Process the blob first
            using (_blobProcessedEvent = new ManualResetEvent(initialState: false))
            using (JobHost host = new JobHost(_hostConfiguration))
            {
                DateTime startTime = DateTime.Now;

                host.Start();
                Assert.True(_blobProcessedEvent.WaitOne(TimeSpan.FromSeconds(60)));

                timeToProcess = (int)(DateTime.Now - startTime).TotalMilliseconds;

                host.Stop();

                Console.SetOut(hold);

                string[] consoleOutputLines = consoleOutput.ToString().Trim().Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
                string[] expectedOutputLines = new string[]
                {
                    "Found the following functions:",
                    "Microsoft.Azure.WebJobs.Host.EndToEndTests.BlobTriggerTests.SingleBlobTrigger",
                    "Job host started",
                    string.Format("Executing: 'BlobTriggerTests.SingleBlobTrigger' - Reason: 'New blob detected: {0}/{1}'", blob.Container.Name, blob.Name),
                    "Executed: 'BlobTriggerTests.SingleBlobTrigger' (Succeeded)",
                    "Job host stopped",
                };
                Assert.True(consoleOutputLines.SequenceEqual(expectedOutputLines));
            }

            // Then start again and make sure the blob doesn't get reprocessed
            // wait twice the amount of time required to process first before 
            // deciding that it doesn't get reprocessed
            using (_blobProcessedEvent = new ManualResetEvent(initialState: false))
            using (JobHost host = new JobHost(_hostConfiguration))
            {
                host.Start();

                bool blobReprocessed = _blobProcessedEvent.WaitOne(2 * timeToProcess);

                host.Stop();

                Assert.False(blobReprocessed);
            }
        }
开发者ID:rafaelmtz,项目名称:azure-webjobs-sdk,代码行数:54,代码来源:BlobTriggerTests.cs

示例8: BlobGetsProcessedOnlyOnce_MultipleHosts

        public void BlobGetsProcessedOnlyOnce_MultipleHosts()
        {
            _testContainer
                .GetBlockBlobReference(BlobName)
                .UploadText("10");

            using (_blobProcessedEvent = new ManualResetEvent(initialState: false))
            using (JobHost host1 = new JobHost(_hostConfiguration))
            using (JobHost host2 = new JobHost(_hostConfiguration))
            {
                host1.Start();
                host2.Start();

                Assert.True(_blobProcessedEvent.WaitOne(TimeSpan.FromSeconds(60)));

                host1.Stop();
                host2.Stop();
            }

            Assert.Equal(1, _timesProcessed);
        }
开发者ID:rafaelmtz,项目名称:azure-webjobs-sdk,代码行数:21,代码来源:BlobTriggerTests.cs

示例9: Stop_WhenUsingTriggeredFunction_TriggersCancellationToken

        public void Stop_WhenUsingTriggeredFunction_TriggersCancellationToken()
        {
            using (JobHost host = new JobHost(_hostConfiguration))
            {
                PrepareHostForTrigger(host, startHost: true);

                host.Stop();

                EvaluateTriggeredCancellation(expectedCancellation: true);
            }
        }
开发者ID:ConnorMcMahon,项目名称:azure-webjobs-sdk,代码行数:11,代码来源:AsyncCancellationEndToEndTests.cs

示例10: Stop_WhenUsingHostCall_DoesNotTriggerCancellationToken

        public void Stop_WhenUsingHostCall_DoesNotTriggerCancellationToken()
        {
            using (JobHost host = new JobHost(_hostConfiguration))
            {
                host.Start();

                Task callTask = InvokeNoAutomaticTriggerFunction(host);

                host.Stop();

                EvaluateNoAutomaticTriggerCancellation(callTask, expectedCancellation: false);
            }
        }
开发者ID:ConnorMcMahon,项目名称:azure-webjobs-sdk,代码行数:13,代码来源:AsyncCancellationEndToEndTests.cs

示例11: MaxDegreeOfParallelism_Queues

        public void MaxDegreeOfParallelism_Queues(int batchSize, int maxExpectedParallelism)
        {
            _receivedMessages = 0;
            _currentSimultaneouslyRunningFunctions = 0;
            _maxSimultaneouslyRunningFunctions = 0;
            _numberOfQueueMessages = batchSize * 3;

            RandomNameResolver nameResolver = new RandomNameResolver();
            JobHostConfiguration hostConfiguration = new JobHostConfiguration()
            {
                NameResolver = nameResolver,
                TypeLocator = new FakeTypeLocator(typeof(ParallelExecutionTests)),
            };
            hostConfiguration.Queues.BatchSize = batchSize;

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(hostConfiguration.StorageConnectionString);
            _queueClient = storageAccount.CreateCloudQueueClient();
            CloudQueue queue = _queueClient.GetQueueReference(nameResolver.ResolveInString(TestQueueName));

            queue.CreateIfNotExists();

            for (int i = 0; i < _numberOfQueueMessages; i++)
            {
                int sleepTimeInSeconds = i % 2 == 0 ? 5 : 1;
                queue.AddMessage(new CloudQueueMessage(sleepTimeInSeconds.ToString()));
            }

            using (_allMessagesProcessed = new ManualResetEvent(initialState: false))
            using (JobHost host = new JobHost(hostConfiguration))
            {
                host.Start();
                _allMessagesProcessed.WaitOne(TimeSpan.FromSeconds(90));
                host.Stop();
            }

            Assert.Equal(_numberOfQueueMessages, _receivedMessages);
            Assert.Equal(0, _currentSimultaneouslyRunningFunctions);

            // the actual value will vary sometimes based on the speed of the machine
            // running the test.
            int delta = _maxSimultaneouslyRunningFunctions - maxExpectedParallelism;
            Assert.True(delta == 0 || delta == 1);
        }
开发者ID:ConnorMcMahon,项目名称:azure-webjobs-sdk,代码行数:43,代码来源:ParallelExecutionTests.cs

示例12: ServiceBusEndToEndInternal

        private void ServiceBusEndToEndInternal(Type jobContainerType, bool verifyLogs = true)
        {
            StringWriter consoleOutput = null;
            if (verifyLogs)
            {
                consoleOutput = new StringWriter();
                Console.SetOut(consoleOutput);
            }

            JobHostConfiguration config = new JobHostConfiguration()
            {
                NameResolver = _nameResolver,
                TypeLocator = new FakeTypeLocator(jobContainerType)
            };
            config.UseServiceBus(_serviceBusConfig);

            string startQueueName = ResolveName(StartQueueName);
            string secondQueueName = startQueueName.Replace("start", "1");
            string queuePrefix = startQueueName.Replace("-queue-start", "");
            string firstTopicName = string.Format("{0}-topic/Subscriptions/{0}-queue-topic-1", queuePrefix);
            string secondTopicName = string.Format("{0}-topic/Subscriptions/{0}-queue-topic-2", queuePrefix);
            CreateStartMessage(_serviceBusConfig.ConnectionString, startQueueName);

            _host = new JobHost(config);

            _topicSubscriptionCalled1 = new ManualResetEvent(initialState: false);
            _topicSubscriptionCalled2 = new ManualResetEvent(initialState: false);

            _host.Start();

            int timeout = 1 * 60 * 1000;
            _topicSubscriptionCalled1.WaitOne(timeout);
            _topicSubscriptionCalled2.WaitOne(timeout);

            // Wait for the host to terminate
            _host.Stop();

            Assert.Equal("E2E-SBQueue2SBQueue-SBQueue2SBTopic-topic-1", _resultMessage1);
            Assert.Equal("E2E-SBQueue2SBQueue-SBQueue2SBTopic-topic-2", _resultMessage2);

            if (verifyLogs)
            {
                string[] consoleOutputLines = consoleOutput.ToString().Trim().Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
                string[] expectedOutputLines = new string[]
                {
                    "Found the following functions:",
                    string.Format("{0}.SBQueue2SBQueue", jobContainerType.FullName),
                    string.Format("{0}.SBQueue2SBTopic", jobContainerType.FullName),
                    string.Format("{0}.SBTopicListener1", jobContainerType.FullName),
                    string.Format("{0}.SBTopicListener2", jobContainerType.FullName),
                    "Job host started",
                    string.Format("Executing: '{0}.SBQueue2SBQueue' - Reason: 'New ServiceBus message detected on '{1}'.'", jobContainerType.Name, startQueueName),
                    string.Format("Executing: '{0}.SBQueue2SBTopic' - Reason: 'New ServiceBus message detected on '{1}'.'", jobContainerType.Name, secondQueueName),
                    string.Format("Executing: '{0}.SBTopicListener1' - Reason: 'New ServiceBus message detected on '{1}'.'", jobContainerType.Name, firstTopicName),
                    string.Format("Executing: '{0}.SBTopicListener2' - Reason: 'New ServiceBus message detected on '{1}'.'", jobContainerType.Name, secondTopicName),
                    "Job host stopped"
                };
                Assert.True(expectedOutputLines.OrderBy(p => p).SequenceEqual(consoleOutputLines.OrderBy(p => p)));
            }
        }
开发者ID:Bjakes1950,项目名称:azure-webjobs-sdk,代码行数:60,代码来源:ServiceBusEndToEndTests.cs


注:本文中的JobHost.Stop方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。