7

Consider me rusty on the subject of asynchronous delegates.

If I want to call a method asynchronously, in a fire-and-forget style, is this an appropriate way to do it?

Action action = DoSomething;
action.BeginInvoke(action.EndInvoke, null);

The DoSomething() method catches all exceptions and deals with them internally.

Is the call to EndInvoke appropriate? Required?

Is there a clearer way to achieve the same behaviour?

Paul Turner
  • 38,949
  • 15
  • 102
  • 166

3 Answers3

11

The new way (in .NET 4) is to do this:

Task.Factory.StartNew(() => DoSomething());
Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
  • 2
    What about disposal of the Task object? I'd be interested in your opinion on [this question](http://stackoverflow.com/q/3734280/119738) – Simon P Stevens Sep 17 '10 at 09:54
5

It should be noted that Task.Factory.StartNew(() => DoSomething()); fails to observe any potential exception thrown by the DoSomething method. I know this is what one wants when starting a fire-and-forget operation, but as far as .Net 4 is concerned, any task with an unobserved exception being finalized by the garbage collector would escalate as an unhandled exception that will kill your process. However, in .Net 4.5, the default behavior has changed (see the async & await keywords).

Steve Czetty
  • 6,147
  • 9
  • 39
  • 48
user1700216
  • 51
  • 1
  • 1
5

The "old-school" way in .NET 3.5 is to use the ThreadPool:

ThreadPool.QueueUserWorkItem(s => DoSomething());

If you prefer to use asynchronous delegates, then you should know that the call to EndInvoke is necessary, even if you don't have any additional code you wish to execute on callback.

Aaronaught
  • 120,909
  • 25
  • 266
  • 342