Subscriber Method Against Event

I noticed a new trend in .NET 4.0, especially in potentially multi-threaded scenarios, which avoids events and provides subscribers methods instead.

For example, System.Threading.Tasks.Task and Task<TResult> have ContinueWith () instead of the Completed or Finished event. Another example is System.Threading.CancellationToken : it has Register () instead of the CancellationRequested event.

While Task.ContinueWith () is logical because it makes it easy to group tasks (not so elegant with events), and also allows Task<TResult> inherit from Task (because in this way Task<TResult> can provide appropriate overloads that would not be possible for the event: if you have an EventHandler event completed in Task, all you can do is create another event, for example, EventHandler<TaskResultEventArgs> Finished in Task<TResult> , which is not very nice) but I cannot find the same explanation for CancellationToken.Register ().

So what are the flaws of events in such scenarios? Should I also follow this pattern? To clarify which of the following to choose? When should I give preference to another?

 public event EventHandler Finished; // or public IDisposable OnFinished(Action continuation) 

Many thanks!

+6
source share
1 answer

I assume that one of the advantages of using subscriber methods is that you have the ability to easily specify the thread your delegate will be running on. See this overload in CancellationToken.Register ().

Update: well, you can actually specify the synchronization context to which your delegate will be sent.

You are right about the trend. This article in the MSDN journal states the following:

New components should not use an event-based asynchronous pattern. Visual Studio Asynchronous Community Technology Preview (CTP) includes a document describing the tasks of an asynchronous template in which components return the task and Task Objects instead of raising events through the SynchronizationContext. Based on API tasks - the future of asynchronous programming in .NET.

And the document in the article talks about

The initiation and completion of an asynchronous operation in TAP is represented by a single method, and thus, there is only one method. This is unlike the IAsyncResult pattern or APM pattern, where BeginMethodName and EndMethodName methods are required, and unlike the event-based asynchronous pattern or EAP, where a MethodNameAsync is required in addition to one or more events, the event has delegate types and EventArg types.

Indeed, taking care of one thing instead of many is good. But this is rather the advantage of TAP over EAP, and not the advantage of subscriber methods.

+2
source

Source: https://habr.com/ru/post/890593/


All Articles