Recently I came across a Microsoft interface with a quite unusual API:
public interface IHostApplicationLifetime
{
public CancellationToken ApplicationStarted { get; }
public CancellationToken ApplicationStopping { get; }
public CancellationToken ApplicationStopped { get; }
}
The documentation of the property ApplicationStopping suggests confusingly that this property is actually an event (emphasis added):
Triggered when the application host is performing a graceful shutdown. Shutdown will block until this event completes.
It seems that what should be a traditional EventHandler event, has been replaced with a CancellationToken property. This is how I expected this
interface to be:
public interface IHostApplicationLifetime
{
public event EventHandler ApplicationStarted;
public event EventHandler ApplicationStopping;
public event EventHandler ApplicationStopped;
}
My question is, are these two notifications mechanisms equivalent? If not, what are the pros and cons of each approach, from the perspective of an API designer? In which circumstances a CancellationToken property is superior to a classic event?
use an event vs a cancellation tokenvery different concepts and meaning altogether. Could you please update your post with what you've tried, what isn't working and expected output?System.Threading.AutoResetEventor ilk, is very different from a cancellation token.CancelationTokencan be baked into a method and make it cancelable. How would you do the same thing with an event? Can you update your question with an example of an alternative of, say, theBlockingCollection<T>.Takemethod, that uses events instead of aCancelationToken?CancellationTokenoverEventHandler. With an EventHandler, you would not know ifApplicationStartedbefore yourEventHandlerregistration ran. This means you would need to add abool IsApplicationStarted { get; }property. TheCancellationTokenwould also implicitely handle lifetime of the Event.