• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# JobHost类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: TestSdkMarkerIsWrittenWhenInAzureWebSites

        public void TestSdkMarkerIsWrittenWhenInAzureWebSites()
        {
            // Arrange
            string tempDir = Path.GetTempPath();
            const string filename = "WebJobsSdk.marker";

            var path = Path.Combine(tempDir, filename);

            File.Delete(path);

            IServiceProvider configuration = CreateConfiguration();

            using (JobHost host = new JobHost(configuration))
            {
                try
                {
                    Environment.SetEnvironmentVariable(WebSitesKnownKeyNames.JobDataPath, tempDir);

                    // Act
                    host.Start();

                    // Assert
                    Assert.True(File.Exists(path), "SDK marker file should have been written");
                }
                finally
                {
                    Environment.SetEnvironmentVariable(WebSitesKnownKeyNames.JobDataPath, null);
                    File.Delete(path);
                }
            }
        }
开发者ID:oaastest,项目名称:azure-webjobs-sdk,代码行数:31,代码来源:JobHostTests.cs


示例2: Main

        static void Main()
        {
            CreateDemoData();

            JobHost host = new JobHost();
            host.RunAndBlock();
        }
开发者ID:andreychizhov,项目名称:microsoft-aspnet-samples,代码行数:7,代码来源:Program.cs


示例3: Run

        public static void Run(string connectionString)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

            CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
            CreateTestQueues(queueClient);

            try
            {
                CloudQueue firstQueue = queueClient.GetQueueReference(_nameResolver.ResolveInString(FunctionChainingPerfTest.FirstQueueName));
                firstQueue.AddMessage(new CloudQueueMessage("Test"));

                _startBlock = MeasurementBlock.BeginNew(0, HostStartMetric);

                JobHostConfiguration hostConfig = new JobHostConfiguration(connectionString);
                hostConfig.NameResolver = _nameResolver;
                hostConfig.TypeLocator = new FakeTypeLocator(typeof(FunctionChainingPerfTest));

                JobHost host = new JobHost(hostConfig);
                _tokenSource = new CancellationTokenSource();
                Task stopTask = null;
                _tokenSource.Token.Register(() => stopTask = host.StopAsync());
                host.RunAndBlock();
                stopTask.GetAwaiter().GetResult();
            }
            finally
            {
                DeleteTestQueues(queueClient);
            }
        }
开发者ID:rafaelmtz,项目名称:azure-webjobs-sdk,代码行数:30,代码来源:FunctionChainingPerfTest.cs


示例4: WebHookDispatcher

 public WebHookDispatcher(WebHooksConfiguration webHooksConfig, JobHost host, JobHostConfiguration config, TraceWriter trace)
 {
     _functions = new ConcurrentDictionary<string, ITriggeredFunctionExecutor>();
     _trace = trace;
     _port = webHooksConfig.Port;
     _types = config.TypeLocator.GetTypes().ToArray();
     _host = host;
 }
开发者ID:JulianoBrugnago,项目名称:azure-webjobs-sdk-extensions,代码行数:8,代码来源:WebHookDispatcher.cs


示例5: ThrowsArgumentNullExceptionIfWorkIsNull

            public void ThrowsArgumentNullExceptionIfWorkIsNull()
            {
                var host = new JobHost();

                var exception = Assert.Throws<ArgumentNullException>(() => host.DoWork(null));

                Assert.Equal("work", exception.ParamName);
            }
开发者ID:regisbsb,项目名称:WebBackgrounder,代码行数:8,代码来源:JobHostFacts.cs


示例6: 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


示例7: StartAsync_WhenNotStarted_DoesNotThrow

 public void StartAsync_WhenNotStarted_DoesNotThrow()
 {
     // Arrange
     using (JobHost host = new JobHost(CreateConfiguration()))
     {
         // Act & Assert
         host.StartAsync().GetAwaiter().GetResult();
     }
 }
开发者ID:oaastest,项目名称:azure-webjobs-sdk,代码行数:9,代码来源:JobHostTests.cs


示例8: CreateAndLogHostStartedAsync

 public async Task<JobHostContext> CreateAndLogHostStartedAsync(JobHost host, CancellationToken shutdownToken, CancellationToken cancellationToken)
 {
     IHostIdProvider hostIdProvider = null;
     if (_config.HostId != null)
     {
         hostIdProvider = new FixedHostIdProvider(_config.HostId);
     }
     return await CreateAndLogHostStartedAsync(host, _storageAccountProvider, _config.Queues, _config.TypeLocator, _config.JobActivator,
         _config.NameResolver, _consoleProvider, _config, shutdownToken, cancellationToken, hostIdProvider);
 }
开发者ID:surenderssm,项目名称:azure-webjobs-sdk,代码行数:10,代码来源:JobHostContextFactory.cs


示例9: Main

        public static void Main()
        {
            // See the AzureJobsData and AzureJobsRuntime in the app.config
            var host = new JobHost();
            var m = typeof(Program).GetMethod("AggregateRss");
            host.Call(m);

            Console.WriteLine(" aggregated to:");
            Console.WriteLine("https://{0}.blob.core.windows.net/blog/output.rss.xml", host.UserAccountName);
        }
开发者ID:amazedsaint,项目名称:RssReaderAzureJobs,代码行数:10,代码来源:Program.cs


示例10: Generate_EndToEnd

        public async Task Generate_EndToEnd()
        {
            // construct our TimerTrigger attribute ([TimerTrigger("00:00:02", RunOnStartup = true)])
            Collection<ParameterDescriptor> parameters = new Collection<ParameterDescriptor>();
            ParameterDescriptor parameter = new ParameterDescriptor("timerInfo", typeof(TimerInfo));
            ConstructorInfo ctorInfo = typeof(TimerTriggerAttribute).GetConstructor(new Type[] { typeof(string) });
            PropertyInfo runOnStartupProperty = typeof(TimerTriggerAttribute).GetProperty("RunOnStartup");
            CustomAttributeBuilder attributeBuilder = new CustomAttributeBuilder(
                ctorInfo,
                new object[] { "00:00:02" },
                new PropertyInfo[] { runOnStartupProperty },
                new object[] { true });
            parameter.CustomAttributes.Add(attributeBuilder);
            parameters.Add(parameter);

            // create the FunctionDefinition
            FunctionMetadata metadata = new FunctionMetadata();
            TestInvoker invoker = new TestInvoker();
            FunctionDescriptor function = new FunctionDescriptor("TimerFunction", invoker, metadata, parameters);
            Collection<FunctionDescriptor> functions = new Collection<FunctionDescriptor>();
            functions.Add(function);

            // Get the Type Attributes (in this case, a TimeoutAttribute)
            ScriptHostConfiguration scriptConfig = new ScriptHostConfiguration();
            scriptConfig.FunctionTimeout = TimeSpan.FromMinutes(5);
            Collection<CustomAttributeBuilder> typeAttributes = ScriptHost.CreateTypeAttributes(scriptConfig);

            // generate the Type
            Type functionType = FunctionGenerator.Generate("TestScriptHost", "TestFunctions", typeAttributes, functions);

            // verify the generated function
            MethodInfo method = functionType.GetMethod("TimerFunction");
            TimeoutAttribute timeoutAttribute = (TimeoutAttribute)functionType.GetCustomAttributes().Single();
            Assert.Equal(TimeSpan.FromMinutes(5), timeoutAttribute.Timeout);
            Assert.True(timeoutAttribute.ThrowOnTimeout);
            Assert.True(timeoutAttribute.TimeoutWhileDebugging);
            ParameterInfo triggerParameter = method.GetParameters()[0];
            TimerTriggerAttribute triggerAttribute = triggerParameter.GetCustomAttribute<TimerTriggerAttribute>();
            Assert.NotNull(triggerAttribute);

            // start the JobHost which will start running the timer function
            JobHostConfiguration config = new JobHostConfiguration()
            {
                TypeLocator = new TypeLocator(functionType)
            };
            config.UseTimers();
            JobHost host = new JobHost(config);

            await host.StartAsync();
            await Task.Delay(3000);
            await host.StopAsync();

            // verify our custom invoker was called
            Assert.True(invoker.InvokeCount >= 2);
        }
开发者ID:Azure,项目名称:azure-webjobs-sdk-script,代码行数:55,代码来源:FunctionGeneratorEndToEndTests.cs


示例11: DoesNotCallStartIfWorkIsAlreadyScheduledOrCompleted

            public void DoesNotCallStartIfWorkIsAlreadyScheduledOrCompleted()
            {
                var tcs = new TaskCompletionSource<object>();
                tcs.SetResult(null);

                var task = tcs.Task;

                var host = new JobHost();

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


示例12: 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


示例13: StartAsync_WhenStarted_Throws

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

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


示例14: QueueMessageLeaseRenew

        /// <summary>
        /// There is a function that takes > 10 minutes and listens to a queue.
        /// </summary>
        /// <remarks>Ignored because it takes a long time. Can be enabled on demand</remarks>
        // Uncomment the Fact attribute to run
        //[Fact(Timeout = 20 * 60 * 1000)]
        public void QueueMessageLeaseRenew()
        {
            _messageFoundAgain = false;

            _queue.AddMessage(new CloudQueueMessage("Test"));

            _tokenSource = new CancellationTokenSource();
            JobHost host = new JobHost(_config);

            _tokenSource.Token.Register(host.Stop);
            host.RunAndBlock();

            Assert.False(_messageFoundAgain);
        }
开发者ID:ConnorMcMahon,项目名称:azure-webjobs-sdk,代码行数:20,代码来源:LeaseExpirationTests.cs


示例15: CreateAndLogHostStartedAsync

        public Task<JobHostContext> CreateAndLogHostStartedAsync(JobHost host, CancellationToken shutdownToken, CancellationToken cancellationToken)
        {
            INameResolver nameResolver = new RandomNameResolver();
            JobHostConfiguration config = new JobHostConfiguration
            {
                NameResolver = nameResolver,
                TypeLocator = TypeLocator
            };

            return JobHostContextFactory.CreateAndLogHostStartedAsync(
                host, StorageAccountProvider, QueueConfiguration, TypeLocator, DefaultJobActivator.Instance, nameResolver, 
                ConsoleProvider, new JobHostConfiguration(), shutdownToken, cancellationToken, HostIdProvider, FunctionExecutor,
                FunctionIndexProvider, BindingProvider, HostInstanceLoggerProvider, FunctionInstanceLoggerProvider,
                FunctionOutputLoggerProvider, BackgroundExceptionDispatcher);
        }
开发者ID:ConnorMcMahon,项目名称:azure-webjobs-sdk,代码行数:15,代码来源:FakeJobHostContextFactory.cs


示例16: CanBindExecutionContext

        public void CanBindExecutionContext()
        {
            JobHostConfiguration config = new JobHostConfiguration
            {
                TypeLocator = new ExplicitTypeLocator(typeof(CoreTestJobs))
            };
            config.UseCore();
            JobHost host = new JobHost(config);

            host.Call(typeof(CoreTestJobs).GetMethod("ExecutionContext"));

            ExecutionContext result = CoreTestJobs.Context;
            Assert.NotNull(result);
            Assert.NotEqual(Guid.Empty, result.InvocationId);
        }
开发者ID:JulianoBrugnago,项目名称:azure-webjobs-sdk-extensions,代码行数:15,代码来源:CoreBindingEndToEndTests.cs


示例17: CreateAndLogHostStartedAsync

        public Task<JobHostContext> CreateAndLogHostStartedAsync(JobHost host, CancellationToken shutdownToken, CancellationToken cancellationToken)
        {
            ITypeLocator typeLocator = new DefaultTypeLocator(new StringWriter(), new DefaultExtensionRegistry());
            INameResolver nameResolver = new RandomNameResolver();
            JobHostConfiguration config = new JobHostConfiguration
            {
                NameResolver = nameResolver,
                TypeLocator = typeLocator
            };

            return JobHostContextFactory.CreateAndLogHostStartedAsync(
                host, StorageAccountProvider, Queues, typeLocator, DefaultJobActivator.Instance, nameResolver,
                new NullConsoleProvider(), new JobHostConfiguration(), shutdownToken, cancellationToken,
                functionIndexProvider: FunctionIndexProvider, singletonManager: SingletonManager);
        }
开发者ID:rafaelmtz,项目名称:azure-webjobs-sdk,代码行数:15,代码来源:TestJobHostContextFactory.cs


示例18: CreateAndLogHostStartedAsync

        public Task<JobHostContext> CreateAndLogHostStartedAsync(JobHost host, CancellationToken shutdownToken, CancellationToken cancellationToken)
        {
            ITypeLocator typeLocator = new DefaultTypeLocator(new StringWriter(), new DefaultExtensionRegistry());
            INameResolver nameResolver = new RandomNameResolver();
            JobHostConfiguration config = new JobHostConfiguration
            {
                NameResolver = nameResolver,
                TypeLocator = typeLocator
            };

            return JobHostContextFactory.CreateAndLogHostStartedAsync(
                host, StorageAccountProvider, config.Queues, typeLocator, DefaultJobActivator.Instance, nameResolver,
                new NullConsoleProvider(), new JobHostConfiguration(), shutdownToken, cancellationToken,
                new FixedHostIdProvider(Guid.NewGuid().ToString("N")),
                null, new EmptyFunctionIndexProvider(),
                null, new NullHostInstanceLoggerProvider(), new NullFunctionInstanceLoggerProvider(), new NullFunctionOutputLoggerProvider(), null, SingletonManager);
        }
开发者ID:ConnorMcMahon,项目名称:azure-webjobs-sdk,代码行数:17,代码来源:TestJobHostContextFactory.cs


示例19: Main

        static void Main(string[] args)
        {
            CancellationTokenSource cancelTokenSource = new CancellationTokenSource();

            FileSystemWatcher watcher = new FileSystemWatcher(@"C:\temp");
            watcher.Created += OnFileCreated;

            host = new JobHost();

            // Run the host on a background thread so we can invoke from dashboard
            host.RunOnBackgroundThread(cancelTokenSource.Token);

            // Enable the file watcher events and wait
            watcher.EnableRaisingEvents = true;
            while (!cancelTokenSource.IsCancellationRequested)
            {
                Thread.Sleep(2000);
            }
        }
开发者ID:rustd,项目名称:WebJobsSDKSamples,代码行数:19,代码来源:Program.cs


示例20: Main

        static void Main(string[] args)
        {
            CloudStorageAccount storageAccount;
            if (CloudStorageAccount.TryParse(
                ConfigurationManager.ConnectionStrings[STORAGE_CONN_STR_KEY_NAME].ConnectionString,
                out storageAccount))
            {
                // Create the queue we're using to trigger on if it doesn't already exist.
                CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
                CloudQueue queue = queueClient.GetQueueReference(PICTURE_LOADER_QUEUE_NAME.ToLower());
                queue.CreateIfNotExists();
            }
            else
            {
                Console.WriteLine("Unable to initialize CloudStorageAccount.");
            }

            JobHost jobHost = new JobHost();
            jobHost.RunAndBlock();
        }
开发者ID:rickrain,项目名称:ContosoDemoWeb,代码行数:20,代码来源:Program.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# JobHostConfiguration类代码示例发布时间:2022-05-24
下一篇:
C# Job类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap