Comment construire un composant de repos avec un très long processus
// One way is to build 3 types of classes
// 1. controller which sends to the
// 2. A class that implements a sender and receiver of messages (messageTransfer)
// 3. A worker that recieves from messageTranfer on a loop (best to use with the infinite loop a cancellation token)
// Response could be in some DB where service will get from it
//Class one:
namespace Example.Controllers
{
[Route("/")]
[ApiController]
public class ExampleController : ControllerBase
{
readonly IRequestSender _requestSender;
public PurgeController(IRequestSender requestSender)
{
_requestSender = requestSender;
}
[HttpPost("example")]
public async Task<IActionResult> Example()
{
//get or create a decription DTO
_requestSender.Send(descDTO);
}
}
}
namespace Example.Impl
{
public class MessageTransfer : IRequestProvider, IRequestSender
{
private readonly IStopTokenProvider _stopTokenProvider;
//Some dataModel (queue, dict)
public MessageTransfer(IStopTokenProvider stopTokenProvider)
{
_stopTokenProvider = stopTokenProvider;
Task.Run(() => MessageTransferRunnerAsync());
}
private async Task MessageTransferRunnerAsync()
{
//loop for keeping DataModel alice
}
}
public bool Send(DescDTO descDTO)
{
if(!_testsDict.TryAdd(descDTO.Type, 1)) //check if you are not handling same handle
return false;
_queue.Enqueue(descDTO);
return true;
}
public DescDTO GetNextAsync(CancellationToken cancellationToken)
{
_queue.TryDequeue(descDTO);
}
}
namespace Example.Impl
{
public class Service
{
readonly IRequestProvider _requestProvider;
public Service(IRequestProvider requestProvider)
{
_requestProvider = requestProvider;
Task.Run(() => RunnerAsync());
}
private async Task RunnerAsync()
{
//loop and every a few seconds: _requestProvider.TryDequeue()
}
}
}
Upvote answer :-)