I have the following TPL Task
public abstract class AggregatorBase : IAggregator
{
public void Start(CancellationToken token)
{
var parent = Task.Factory.StartNew(x =>
{
Aggregate(token);
},TaskCreationOptions.LongRunning, token);
parent.Wait();
}
public abstract void Aggregate(CancellationToken ct);
}
within the Aggregate method implementations I have a number of Observable.Subscription’s ending with the following
public override void Aggregate(CancellationToken ct)
{
this.observables.Subscribe(// Do stuff);
this.observables.Subscribe(// Do more stuff);
while (!token.IsCancellationRequested)
{
System.Threading.Thread.Sleep(1000)
}
}
Question is whats the best way of keeping the Task alive and all Subscriptions active without spinning?
wait on the cancellation token’s wait handle:
EDIT:
if you don’t have any periodic work to do on this thread, then simply use the
WaitOneoverload without a timeout parameter.that will wait indefinetly until the cancellation token is signalled, then continue.
EDIT2:
I just read that you said you had that while loop within the observable’s subscriptions. It should be just after you have setup all your observables subscriptions, but not within each actual subscription callback (those subscriptions will run on whatever thread invoked the source event(s) or possibly other thread pool threads, not the task thread that setup the subscriptions).