Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantages of using standard .Net Async patterns?

I am designing a class that performs long running tasks. The first design I came up with was:

public TaskHandle DoSomethingAsync(DoSomethingCompleteCallback completedCallback);
public void       CancelDoSomething(TaskHandle handle);

This is simple and concise. However, I am wondering if I should implement it as one of the standard .Net async patterns I have been reading about?

APM:

public IAsyncResult BeginDoSomething(AsyncCallback completedCallback, Object stateObject);
public void         EndDoSomething(IAsyncResult asyncResult);

EAP:

public void  DoSomethingAsync(string param, object userState);
public event DoSomethingCompletedEventHandler DoSomethingCompleted;

IMO these seem to complicate the interface for no real advantage other than being patterns recognisable to other .Net developers. APM requires client code to always call EndDoSomething() even in their completedCallback, and EAP requires separate subscription to the completed event.

What are the advantages, if any, of using the standard patterns that I am missing?

like image 840
GazTheDestroyer Avatar asked Nov 23 '11 10:11

GazTheDestroyer


1 Answers

The only advantages of these patterns is that they are instantly recognisable to other developers and may have framework support (eg begin end support in WCF).

However with the introduction of the TPL an .Net4 and further integration in the new .Net4.5 release it appears .Net is moving away from the IAsyncResult / Begin End paradigms and more towards Task based asynchrony (IMHO preferable).

So, to throw the new way into the mix:

public Task DoSomethingAsync(string param);

And then all operations relating to cancelling/accessing results are available on the Task object, which allows for proper abstraction of the async mechanism since any consumers only rely on a Task rather than the 'initiator' of the work AND the handle that is returned.

like image 180
Rich O'Kelly Avatar answered Sep 22 '22 13:09

Rich O'Kelly