I want to process a Request.Body
in a background-service in ASP.Net Core, so I first add it to a ConcurrentQueue.
public class BackgroundJobs
{
public ConcurrentQueue<Stream> Queue { get; set; } = new ConcurrentQueue<Stream>();
}
The concurrentQueue is instantiated with AddSingleton
in Startup.cs
[ApiController]
public class NotificationsController : ControllerBase
{
private readonly BackgroundJobs backgroundJobs;
public NotificationsController( BackgroundJobs backgroundJobs)
{
this.backgroundJobs = backgroundJobs;
}
//...........
[HttpPost]
public ActionResult<string> Post([FromQuery] string validationToken = null)
{
if (!string.IsNullOrEmpty(validationToken))
{
return Ok(validationToken);
}
else
{
backgroundJobs.Queue.Enqueue(Request.Body);
return Accepted();
}
}
}
BackgroundServices.cs was instantiated in Startup.cs with AddHostedService
.
When the Request.Body
is in the queue I want to process it further.
public class BackgroundServices : BackgroundService, IHostedService
{
private readonly BackgroundJobs backgroundJobs;
private IServiceScopeFactory iServiceScopeFactory;
public BackgroundServices(BackgroundJobs backgroundJobs, IServiceScopeFactory iServiceScopeFactory)
{
this.backgroundJobs = backgroundJobs;
this.iServiceScopeFactory = iServiceScopeFactory;
}
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
Stream stream;
while (!cancellationToken.IsCancellationRequested)
{
if (this.backgroundJobs.Queue.TryDequeue(out stream))
{
StreamReader streamReader = new StreamReader(stream);
string content = await streamReader.ReadToEndAsync();
var list = JsonConvert.DeserializeObject<Notifications>(content)
//......
But get on string content = await streamReader.ReadToEndAsync()
the following error message: System.ObjectDisposedException in System.Private.CoreLib.dll