C# 可以挂起并行运行的后台作业数

C# 可以挂起并行运行的后台作业数,c#,hangfire,hangfire-sql,C#,Hangfire,Hangfire Sql,我有一个IO密集型方法,我正在使用hangfire作为后台作业运行 public IHttpActionResult Request(int[] ids) { foreach(var id in ids) { BackgroundJob.Enqueue<IMyService>(x => x.DoWork(id)); } } public IHttpActionResult请求(int[]ids) { foreach(id中的变量id) {

我有一个IO密集型方法,我正在使用hangfire作为后台作业运行

public IHttpActionResult Request(int[] ids)
{
    foreach(var id in ids)
    {
       BackgroundJob.Enqueue<IMyService>(x => x.DoWork(id));
    }
}
public IHttpActionResult请求(int[]ids)
{
foreach(id中的变量id)
{
BackgroundJob.Enqueue(x=>x.DoWork(id));
}
}
因此,对于每个id,我将一个后台作业排入队列,hangfire会按照预期立即调用
DoWork()
。然而,
DoWork
是IO密集型的。因此,如果我有100多个ID,它需要大量的CPU功率和带宽


是否有办法限制Hangfire中后台作业的数量

您可以使用Hangfire并设置该队列的工作人员数量

在hangfire启动配置中,设置以下队列:

var options = new BackgroundJobServerOptions
{
    Queues = new[] { "default" }, // You can have multiple queues and multiple worker counts.. check hangfire documentation
    WorkerCount = 5 // this is up to you
};

app.UseHangfireServer(options);
请参见下面的代码示例:

public IHttpActionResult Request(int[] ids)
{
    foreach(var id in ids)
    {
       BackgroundJob.Enqueue<IMyService>(x => x.DoWork(id));
    }
}


[Queue("default")]// add this attribute on your function
public void DoWork() { 
    //Magical IO code here
}
public IHttpActionResult请求(int[]ids)
{
foreach(id中的变量id)
{
BackgroundJob.Enqueue(x=>x.DoWork(id));
}
}
[队列(“默认”)]//在函数上添加此属性
公共无效DoWork(){
//这里有神奇的IO代码
}
如果您需要更多信息,我建议您查看以下hangfire文档:


希望这对您有所帮助。

我发现以前没有使用过此功能。。我使用过此功能后,它也可以解决您的问题:-)是的
MaximumConcurrentExecutions
有效。我注意到的一件事是,我正在使用
Unity
表示DI。如果您使用interface
BackgroundJob.Enqueue(x=>x.DoWork(id))注册后台作业;然后您必须在接口中的方法定义上添加
MaximumConcurrentExecutions`属性,而不是在具体的ClassInTesting中。谢谢你的更新。看来你解决了自己的问题。请发布您的答案,以便我可以投票给您:-)因此在
MaximumConcurrentExecutionsAttribute
中又遇到了一个问题。小于
20
MaxConcurrentJobs
的任何值都能按预期工作,但大于
20的任何值只执行20个作业。例如
[MaximumConcurrentExecutions(10012010)]
一次只执行20个作业