Decoupling caller from callee in C# using delegate/BeginInvoke

420 Views Asked by At

In C# I have a hierarchy of classes that perform actions that could potentially take a long time. For this reason, I implemented a decoupling/callback mechanism so the caller is not blocked, but is informed of an action's completion through a callback interface. This looks something like this:

protected delegate void ActionDelegate();
public void doAction()
{
  Task.Factory.StartNew(() => DoActionASync());
}
private void DoActionASync()
{
  DoActionImpl(); 
  Caller->ActionDone(); // Caller is registered separately, and implements an interface (ICallback) that includes this function
}
protected abstract void DoActionImpl(); // Derived classes implement this

This is quite a lot of code that is repeated with minor differences (in signature) for each method. My question is whether this is the right way to approach this, or does .NET/C# offer any constructs that would make this easier/less verbose?

1

There are 1 best solutions below

2
On BEST ANSWER

There is good documentation on asynchronous programming patterns on MSDN. If you are using .NET 4, you should look into the Task Parallel Library (TPL).

Asynchronous programming using delegates is covered here (there is also an extra example). You could do much worse that follow MSDN's practices and suggestions.