我将控制台应用程序作为Windows服务启动,并具有以下代码:
class Program
{
[STAThread]
static async Task Main(string[] args)
{
await new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<MyService>();
services.AddTransient<IConfiguration>(
(service) => new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("config.json")
.Build());
})
.RunConsoleAsync();
}
}
和以下MyService
代码:
public class MyService : IHostedService, IDisposable
{
private Timer _timer;
CloudQueue _queue;
public MyService(IConfiguration configuration)
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(configuration.GetSection("ConnectionStrings:StorageConnectionString").Value);
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
_queue = queueClient.GetQueueReference(configuration.GetSection("Queue:OrganizationRegistration").Value);
}
public Task StartAsync(CancellationToken cancellationToken)
{
Console.WriteLine("Timed Background Service is starting.");
//_timer = new Timer(DoWork, null, TimeSpan.Zero,
// TimeSpan.FromSeconds(5));
return Task.CompletedTask;
}
private async Task DoWorkAsync(object state)
{
var message = _queue.GetMessageAsync();
// long action
}
public Task StopAsync(CancellationToken cancellationToken)
{
Console.WriteLine("Timed Background Service is stopping.2");
//_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public void Dispose()
{
_timer?.Dispose();
}
}
我想收听Azure队列,如果存在消息,则执行长时间操作。如何正确实施?我本来想通过Timer
来做的,但是我不想在第一次执行时再执行一次操作。