Edition 0 Updated to asp. Net core 0



Yüklə 11,82 Mb.
Pdf görüntüsü
səhifə146/288
tarix12.07.2023
ölçüsü11,82 Mb.
#136458
1   ...   142   143   144   145   146   147   148   149   ...   288
NET-Microservices-Architecture-for-Containerized-NET-Applications


public
abstract
class
BackgroundService : IHostedService, IDisposable 

private
Task _executingTask; 
private
readonly
CancellationTokenSource _stoppingCts = 
new
CancellationTokenSource
(); 
protected
abstract
Task 
ExecuteAsync
(CancellationToken stoppingToken); 
public
virtual
Task 
StartAsync
(CancellationToken cancellationToken) 

// Store the task we're executing
_executingTask = 
ExecuteAsync
(_stoppingCts.
Token
); 
// If the task is completed then return it,
// this will bubble cancellation and failure to the caller
if
(_executingTask.
IsCompleted


return
_executingTask; 

// Otherwise it's running
return
Task.
CompletedTask


public
virtual
async Task 
StopAsync
(CancellationToken cancellationToken) 

// Stop called without start
if
(_executingTask == 
null


return




161 
CHAPTER 5 | Designing and Developing Multi-Container and Microservice-Based .NET Applications 
try

// Signal cancellation to the executing method
_stoppingCts.
Cancel
(); 

finally

// Wait until the task completes or the stop token triggers
await Task.
WhenAny
(_executingTask, Task.
Delay
(Timeout.
Infinite

cancellationToken)); 


public
virtual
void
Dispose
() 

_stoppingCts.
Cancel
(); 


When deriving from the previous abstract base class, thanks to that inherited implementation, you just 
need to implement the 
ExecuteAsync()
method in your own custom hosted service class, as in the 
following simplified code from eShopOnContainers which is polling a database and publishing 
integration events into the Event Bus when needed. 

Yüklə 11,82 Mb.

Dostları ilə paylaş:
1   ...   142   143   144   145   146   147   148   149   ...   288




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin