本文整理汇总了C#中JobHost.Start方法的典型用法代码示例。如果您正苦于以下问题:C# JobHost.Start方法的具体用法?C# JobHost.Start怎么用?C# JobHost.Start使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类JobHost
的用法示例。
在下文中一共展示了JobHost.Start方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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);
}
}
}
示例2: 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.");
}
}
示例3: 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);
}
}
示例4: 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);
}
示例5: Main
static void Main(string[] args)
{
using (var listener = new ObservableEventListener())
{
listener.LogToConsole(new ConsoleFormatter());
listener.EnableEvents(EngineEventSource.Log, EventLevel.Verbose, Keywords.All);
listener.EnableEvents(TableStorageEventSource.Log, EventLevel.Verbose, Keywords.All);
var eventContext = new TableStorageJobEventContext(
CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageAccount")));
var host = new JobHost(eventContext);
host.Add(new LogCleanupJob());
host.Add(new SendNewsletterJob());
host.Add(new LongRunningJob());
host.Start();
Console.WriteLine("Waiting...");
Console.ReadLine();
}
}
示例6: Queue_IfNameIsInvalid_ThrowsDuringIndexing
public void Queue_IfNameIsInvalid_ThrowsDuringIndexing()
{
IStorageAccount account = CreateFakeStorageAccount();
TaskCompletionSource<object> backgroundTaskSource = new TaskCompletionSource<object>();
IServiceProvider serviceProvider = FunctionalTest.CreateServiceProviderForCallFailure(account,
typeof(InvalidQueueNameProgram), backgroundTaskSource);
using (JobHost host = new JobHost(serviceProvider))
{
// Act & Assert
FunctionIndexingException exception = Assert.Throws<FunctionIndexingException>(() => host.Start());
Assert.Equal("Error indexing method 'InvalidQueueNameProgram.Invalid'", exception.Message);
Exception innerException = exception.InnerException;
Assert.IsType<ArgumentException>(innerException);
ArgumentException argumentException = (ArgumentException)innerException;
Assert.Equal("name", argumentException.ParamName);
string expectedMessage = String.Format(CultureInfo.InvariantCulture,
"The dash (-) character may not be the first or last letter - \"-illegalname-\"{0}Parameter " +
"name: name", Environment.NewLine);
Assert.Equal(expectedMessage, innerException.Message);
Assert.Equal(TaskStatus.WaitingForActivation, backgroundTaskSource.Task.Status);
}
}
示例7: 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
示例8: StopAsync_WhenAlreadyStopping_ReturnsSameTask
public void StopAsync_WhenAlreadyStopping_ReturnsSameTask()
{
// Arrange
using (JobHost host = new JobHost(CreateConfiguration()))
{
host.Start();
// Replace (and cleanup) the existing listener to hook StopAsync.
IListener oldRunner = host.Listener;
oldRunner.StopAsync(CancellationToken.None).GetAwaiter().GetResult();
TaskCompletionSource<object> stopTaskSource = new TaskCompletionSource<object>();
Mock<IListener> listenerMock = new Mock<IListener>(MockBehavior.Strict);
listenerMock.Setup(r => r.StopAsync(It.IsAny<CancellationToken>())).Returns(stopTaskSource.Task);
listenerMock.Setup(r => r.Dispose());
host.Listener = listenerMock.Object;
Task alreadyStopping = host.StopAsync();
// Act
Task stoppingAgain = host.StopAsync();
// Assert
Assert.Same(alreadyStopping, stoppingAgain);
// Cleanup
stopTaskSource.SetResult(null);
alreadyStopping.GetAwaiter().GetResult();
stoppingAgain.GetAwaiter().GetResult();
}
}
示例9: 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();
}
}
示例10: StartAsync_WhenStopping_Throws
public void StartAsync_WhenStopping_Throws()
{
// Arrange
using (JobHost host = new JobHost(CreateConfiguration()))
{
host.Start();
// Replace (and cleanup) the exsiting runner to hook StopAsync.
IListener oldListener = host.Listener;
oldListener.StopAsync(CancellationToken.None).GetAwaiter().GetResult();
TaskCompletionSource<object> stopTaskSource = new TaskCompletionSource<object>();
Mock<IListener> listenerMock = new Mock<IListener>(MockBehavior.Strict);
listenerMock.Setup(r => r.StopAsync(It.IsAny<CancellationToken>())).Returns(stopTaskSource.Task);
listenerMock.Setup(r => r.Dispose());
host.Listener = listenerMock.Object;
Task stopping = host.StopAsync();
// Act & Assert
ExceptionAssert.ThrowsInvalidOperation(() => host.StartAsync(), "Start has already been called.");
// Cleanup
stopTaskSource.SetResult(null);
stopping.GetAwaiter().GetResult();
}
}
示例11: 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();
}
示例12: PrepareHostForTrigger
private void PrepareHostForTrigger(JobHost host, bool startHost)
{
host.Call(typeof(AsyncCancellationEndToEndTests).GetMethod("WriteQueueMessage"));
if (startHost)
{
host.Start();
Assert.True(_functionStarted.WaitOne(DefaultTimeout));
}
}
示例13: 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);
}
}
示例14: 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);
}
示例15: 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)));
}
}