C# 后台服务结束分配的任务后会发生什么?
接下来,我实现了一个库,允许我的web API在后台创建和运行任务。基本上,我要做的是创建一个C# 后台服务结束分配的任务后会发生什么?,c#,asp.net-core,asp.net-core-2.0,asp.net-core-hosted-services,C#,Asp.net Core,Asp.net Core 2.0,Asp.net Core Hosted Services,接下来,我实现了一个库,允许我的web API在后台创建和运行任务。基本上,我要做的是创建一个QueuedHostedService(它继承自BackgroundService),其中包含要完成的任务并将其添加到队列中。然后,通过同时运行这些任务(我想是在不同的线程上),这个队列会逐渐清空。下面是BackgroundService public abstract class BackgroundService : IHostedService, IDisposable { protect
QueuedHostedService
(它继承自BackgroundService
),其中包含要完成的任务并将其添加到队列中。然后,通过同时运行这些任务(我想是在不同的线程上),这个队列会逐渐清空。下面是BackgroundService
public abstract class BackgroundService : IHostedService, IDisposable
{
protected BackgroundService();
public virtual void Dispose();
//
// Summary:
// Triggered when the application host is ready to start the service.
//
// Parameters:
// cancellationToken:
// Indicates that the start process has been aborted.
public virtual Task StartAsync(CancellationToken cancellationToken);
//
// Summary:
// Triggered when the application host is performing a graceful shutdown.
//
// Parameters:
// cancellationToken:
// Indicates that the shutdown process should no longer be graceful.
[AsyncStateMachine(typeof(<StopAsync>d__4))]
public virtual Task StopAsync(CancellationToken cancellationToken);
//
// Summary:
// This method is called when the Microsoft.Extensions.Hosting.IHostedService starts.
// The implementation should return a task that represents the lifetime of the long
// running operation(s) being performed.
//
// Parameters:
// stoppingToken:
// Triggered when Microsoft.Extensions.Hosting.IHostedService.StopAsync(System.Threading.CancellationToken)
// is called.
//
// Returns:
// A System.Threading.Tasks.Task that represents the long running operations.
protected abstract Task ExecuteAsync(CancellationToken stoppingToken);
为什么您认为必须从这些方法返回一个
任务
,让系统有效地知道您何时完成了任务?这可能会有所帮助。是否需要清理任何内容取决于您的实际实现,例如您的服务类是否包含任何需要处理的项。文档中显示的排队任务处理器只是一个简单的示例,不需要更多。电子邮件处理者可能会对电子邮件消息进行排队,并使用例如MailKit发送消息。在这种情况下,停止可能包括处理任何客户端对象。@Danielasartori不,您不需要。柯克·拉金指着那张桌子。调用StopAsync()
将发出取消的信号token@DanieleSartori最后一个注意事项-在代码中,BackgroundService.Dispose()
也表示取消。这意味着,当DI容器终止并在所有IDisposable
实例上调用Dispose()
时,它也会在服务上调用它,告诉它们停止
public class QueuedHostedService : BackgroundService
{
private static ILog logger = LogExtensions.GetClassLogger();
public QueuedHostedService(IBackgroundTaskQueue taskQueue)
{
TaskQueue = taskQueue;
}
public IBackgroundTaskQueue TaskQueue { get; }
protected async override Task ExecuteAsync(CancellationToken cancellationToken)
{
logger.MethodEnter();
while (!cancellationToken.IsCancellationRequested)
{
var workItem = await TaskQueue.DequeueAsync(cancellationToken);
try
{
await workItem(cancellationToken);
}
catch (Exception ex)
{
logger.Error($"Error occurred executing {nameof(workItem)}. with the following exception {ex.Message}");
}
}
logger.MethodLeave();
}
}